Python inflect 模块,engine() 实例源码

我们从Python开源项目中,提取了以下37个代码示例,用于说明如何使用inflect.engine()

项目:django-magic-cards    作者:pbaranay    | 项目源码 | 文件源码
def handle(self, *args, **options):
        models_to_track = [Set, Card, Printing]
        initial = {model: model.objects.count() for model in models_to_track}

        p = inflect.engine()
        set_codes = options['set_code']
        if set_codes:
            count = len(set_codes)
            set_string = 'num({count}) plural_noun(set) ({codes})'.format(count=count, codes=', '.join(set_codes))
        else:
            set_string = 'all sets'

        self.stdout.write(p.inflect("Beginning import of {}.".format(set_string)))
        import_cards(set_codes or Everything)
        self.stdout.write("Import complete.")

        final = {model: model.objects.count() for model in models_to_track}
        status_strings = [
            p.inflect(
                "{0} new num({0},)plural_noun({1})".format(final[model] - initial[model], model._meta.object_name))
            for model in models_to_track
        ]
        self.stdout.write("Added {}.".format(p.join(status_strings)))
项目:pyagram    作者:hideshi    | 项目源码 | 文件源码
def syntactic_analysis(self, src):
        i = inflect.engine()
        relations = {}
        foreign_keys = {}
        for table in src:
            for k, v in table.items():
                if k == 'table_name':
                    foreign_keys[(i.singular_noun(v) if i.singular_noun(v) else v) + '_id'] = v
        for table in src:
            for k, v in table.items():
                if k == 'table_name':
                    table_name = v
            for e in table:
                if 'column_name' in e:
                    if e['column_name'] in foreign_keys.keys():
                        relations[table_name + ':' + e['column_name']] = foreign_keys[e['column_name']] + ':id'
        result = {}
        result['src'] = src
        result['relations'] = relations
        return result
项目:tcex    作者:ThreatConnect-Inc    | 项目源码 | 文件源码
def __init__(self):
        """
        """
        # init inflect engine
        self.inflect = inflect.engine()

        # Required Argument
        # self._parsed = False  # only parse once from user
        self._config = {}
        self._parser = argparse.ArgumentParser()

        self._install_json = {}
        # self.load_install_json()
        self._app_packages = []

        self._required_arguments()
        self._args, self._extra_args = self._parser.parse_known_args()

        # Get instance of vault (after args are passed)
        self._vault = TcExVault(self.args.vault_url, self.args.vault_token)
项目:beckett    作者:phalt    | 项目源码 | 文件源码
def get_resource_url(cls, resource, base_url):
        """
        Construct the URL for talking to this resource.

        i.e.:

        http://myapi.com/api/resource

        Note that this is NOT the method for calling individual instances i.e.

        http://myapi.com/api/resource/1

        Args:
            resource: The resource class instance
            base_url: The Base URL of this API service.
        returns:
            resource_url: The URL for this resource
        """
        if resource.Meta.resource_name:
            url = '{}/{}'.format(base_url, resource.Meta.resource_name)
        else:
            p = inflect.engine()
            plural_name = p.plural(resource.Meta.name.lower())
            url = '{}/{}'.format(base_url, plural_name)
        return cls._parse_url_and_validate(url)
项目:restful-api-guidelines-linter    作者:hjacobs    | 项目源码 | 文件源码
def lint_plural_resource_names(spec, resolver):
    """
    Must: Pluralize Resource Names

    https://zalando.github.io/restful-api-guidelines/naming/Naming.html#must-pluralize-resource-names
    """
    inflect_engine = inflect.engine()
    for path_name, methods_available in spec.get('paths', {}).items():
        path_name_without_variables = re.sub('{[^}]*}', '', path_name)
        for segment in path_name_without_variables.split('/'):
            if segment != '.well-known':
                resource = ' '.join(segment.split('-'))
                if resource:
                    singular = inflect_engine.singular_noun(resource)
                    plural = inflect_engine.plural_noun(resource)
                    if singular == resource or (not singular and plural and plural != resource):
                        yield 'paths/"{}"'.format(path_name), '"{}" is not in plural form'.format(resource)
项目:open-syllabus-project    作者:davidmcclure    | 项目源码 | 文件源码
def blacklisted_titles(self):

        """
        Pluralize the blacklisted titles.

        Returns: list
        """

        p = inflect.engine()

        singulars = self.config.get('blacklisted_titles', [])

        return map(
            tokenize_field,
            singulars + [p.plural(s) for s in singulars],
        )
项目:exercism-python    作者:amalshehu    | 项目源码 | 文件源码
def verse(v):
    p = inflect.engine()
    day = p.number_to_words(v)
    day_count = p.ordinal(day)
    if v == 1:
        lyric = "On the %s day of Christmas my true love gave" \
                "to me, " % (day_count)
        lyric = lyric + gifts[v]
        return lyric
    if v > 1:
        lyric = "On the %s day of Christmas my true love gave" \
                "to me, " % (day_count)
        for k in range(v, 1, -1):
            num = p.number_to_words(k)
            lyric = lyric + num + " " + gifts[k] + ", "
        lyric += "and " + gifts[1]
        return lyric
项目:threatconnect-developer-docs    作者:ThreatConnect-Inc    | 项目源码 | 文件源码
def __init__(self):
        """
        """
        # init inflect engine
        self.inflect = inflect.engine()

        # Required Argument
        # self._parsed = False  # only parse once from user
        self._config = {}
        self._parser = argparse.ArgumentParser()

        self._install_json = {}
        # self.load_install_json()
        self._app_packages = []

        self._required_arguments()
        self._args, self._extra_args = self._parser.parse_known_args()

        # Get instance of vault (after args are passed)
        self._vault = TcExVault(self.args.vault_url, self.args.vault_token)
项目:mutant    作者:peterdemin    | 项目源码 | 文件源码
def make_entity_name(field_name):
        inflector = inflect.engine()
        return (inflector.singular_noun(field_name) or field_name).title()
项目:mutant    作者:peterdemin    | 项目源码 | 文件源码
def inflector():
    global __inflector
    if __inflector is None:
        __inflector = inflect.engine()
    return __inflector
项目:smt-for-gec    作者:cnap    | 项目源码 | 文件源码
def __init__(self):
        self.WN_TAGS = {'J': 'a', 'N': 'n', 'R': 'r', 'V': 'v'}
        self.wnl = WordNetLemmatizer()
        self.dictionary = enchant.Dict('en')
        self.inflengine = inflect.engine()
项目:teach-me-aws-stepfunctions    作者:OsamaJBR    | 项目源码 | 文件源码
def lambda_handler(event,context):
    inflect_engine = inflect.engine()
    number = inflect_engine.number_to_words(event['final_number'])
    message = {"DelMeMessage": "The StepFunctions Result is %r" %number}
    client = boto3.client('sns')
    response = client.publish(
        TargetArn="SNS-TOPIC-ARN",
        Message=json.dumps({'default': json.dumps(message)}),
        MessageStructure='json'
    )
项目:nanosat-control    作者:ceyzeriat    | 项目源码 | 文件源码
def camelize_singular(txt):
    """
    Produce a 'camelized' and singular class name.
    e.g. 'the_underscores' -> 'TheUnderscore'
    """
    camelize = str(txt[0].upper() +\
                    re.sub(r'_([a-z])',
                           lambda m: m.group(1).upper(), txt[1:]))
    return inflect.engine().singular_noun(camelize)
项目:nanosat-control    作者:ceyzeriat    | 项目源码 | 文件源码
def camelize_singular_rev(txt):
    """
    Produce a 'decamelized' and plural class name.
    e.g. 'TheUnderscore' -> 'the_underscores'
    """
    decamelize = str(txt[0].lower() +\
                    re.sub(r'([A-Z])',
                           lambda m: '_'+m.group(1).lower(), txt[1:]))
    return inflect.engine().plural_noun(decamelize)
项目:nanosat-control    作者:ceyzeriat    | 项目源码 | 文件源码
def camelize_singular(txt):
    """
    Produce a 'camelized' and singular class name.
    e.g. 'the_underscores' -> 'TheUnderscore'
    """
    camelize = str(txt[0].upper() +\
                    re.sub(r'_([a-z])',
                           lambda m: m.group(1).upper(), txt[1:]))
    return inflect.engine().singular_noun(camelize)
项目:nanosat-control    作者:ceyzeriat    | 项目源码 | 文件源码
def camelize_singular_rev(txt):
    """
    Produce a 'decamelized' and plural class name.
    e.g. 'TheUnderscore' -> 'the_underscores'
    """
    decamelize = str(txt[0].lower() +\
                    re.sub(r'([A-Z])',
                           lambda m: '_'+m.group(1).lower(), txt[1:]))
    return inflect.engine().plural_noun(decamelize)
项目:Entity-Triple-Entity-Extraction    作者:shubham0420    | 项目源码 | 文件源码
def __init__(self):
        self.Month_Dict= {'01':'January',"02":'February',"03":'March','04':'April','05':'May','06':'June','07':'July','08':'August','09':'September','10':'October','11':'November','12':'December '}
        self.month = None
        self.date = None
        self.year = None
        self.Number = None
        self.Inflect = inflect.engine()
        self.Combination = []
项目:spikes    作者:mozilla    | 项目源码 | 文件源码
def send_email(emails=[], date='today'):
    significants, bugs_by_signature, totals = get(date=date)
    r = prepare(significants, bugs_by_signature, totals, date)
    if r:
        results, spikes_number, urls, affected_chans, yesterday, today = r
        env = Environment(loader=FileSystemLoader('templates'))
        template = env.get_template('startup_crashes_email')
        spikes_number_word = inflect.engine().number_to_words(spikes_number)
        body = template.render(spikes_number=spikes_number,
                               spikes_number_word=spikes_number_word,
                               totals=totals,
                               start_date=yesterday,
                               end_date=today,
                               results=results,
                               urls=urls)

        chan_list = ', '.join(affected_chans)
        title = 'Spikes in startup crashes in {} the {}'
        title = title.format(chan_list, today)
        if emails:
            mail.send(emails, title, body, html=True)
        else:
            with open('/tmp/foo.html', 'w') as Out:
                Out.write(body)
            print('Title: %s' % title)
            print('Body:')
            print(body)
项目:sqlacodegen    作者:agronholm    | 项目源码 | 文件源码
def create_inflect_engine(self):
        if self.noinflect:
            return _DummyInflectEngine()
        else:
            import inflect
            return inflect.engine()
项目:ttbp    作者:modgethanc    | 项目源码 | 文件源码
def start():
    '''
    main engine head

    * called on program start
    * calls config check
    * proceeds to main menu
    * handles ^c and ^d ejects
    '''

    redraw()
    print("""
if you don't want to be here at any point, press <ctrl-d> and it'll all go away.
just keep in mind that you might lose anything you've started here.\
""")

    try:
        print(check_init())
    except EOFError:
        print(stop())
        return

    ##
    redraw()

    while 1:
        try:
            print(main_menu())
        except EOFError:
            print(stop())
            break
        except KeyboardInterrupt:
            redraw(EJECT)
        else:
            break
项目:ttbp    作者:modgethanc    | 项目源码 | 文件源码
def start():
    '''
    main engine head

    * called on program start
    * calls config check
    * proceeds to main menu
    * handles ^c and ^d ejects
    '''

    redraw()
    print("""
if you don't want to be here at any point, press <ctrl-d> and it'll all go away.
just keep in mind that you might lose anything you've started here.\
""")

    try:
        print(check_init())
    except EOFError:
        print(stop())
        return

    ##
    redraw()

    while 1:
        try:
            print(main_menu())
        except EOFError:
            print(stop())
            break
        except KeyboardInterrupt:
            redraw(EJECT)
        else:
            break
项目:Canella-CMS    作者:mush42    | 项目源码 | 文件源码
def gen_default_api_endpoints(cls):
        e = engine()
        model_name = cls.schema.Meta.model.__name__.lower()
        identifier = e.plural(model_name)
        rv = {
            '/%s/' %identifier: {
                'endpoint': '%s-collection' %model_name,
                'methods': ['GET', 'POST']
            },
            '/%s/<int:pk>/' %identifier: {
                'endpoint': '%s-resource' %model_name,
                'methods': ['GET', 'PUT', 'DELETE']
            },
        }
        return rv
项目:brainforks    作者:minervax    | 项目源码 | 文件源码
def get_synonyms(word):
    pluralizer = inflect.engine()

    syn_set = []
    wnsynset = wn.synsets(word)


    for i in range(0, len(wnsynset)):

        for lemma in wnsynset[i].lemma_names():

            syn_set.append(lemma.lower())

# adds plurals and removes dups

    syn_setnodup = []
    for item in syn_set:
        if item not in syn_setnodup:
            syn_setnodup.append(item)

    syn_set_final = []
    for item in syn_setnodup:
        syn_set_final.append(item)
        syn_set_final.append(pluralizer.plural(item))


    return syn_set_final
项目:word_forms    作者:gutfeeling    | 项目源码 | 文件源码
def singularize(noun):
    """
    args
        - noun : a noun e.g "man"

    returns the singular form of the word if it finds one. Otherwise,
    returns the word itself.
    """
    singular = inflect.engine().singular_noun(noun)
    if singular in ALL_WORDNET_WORDS:
        return singular
    return noun
项目:word_forms    作者:gutfeeling    | 项目源码 | 文件源码
def get_word_forms(word):
    """
    args
        word : a word e.g "love"

    returns the related word forms corresponding to the input word. the output
    is a dictionary with four keys "n" (noun), "a" (adjective), "v" (verb)
    and "r" (adverb). The value for each key is a python Set containing
    related word forms with that part of speech.

    e.g. {'a': {'lovable', 'loveable'},
          'n': {'love', 'lover', 'lovers', 'loves'},
          'r': set(),
          'v': {'love', 'loved', 'loves', 'loving'}}
    """
    word = singularize(word)
    related_lemmas = get_related_lemmas(word)
    related_words_dict = {"n" : set(), "a" : set(), "v" : set(), "r" : set()}
    for lemma in related_lemmas:
        pos = lemma.synset().pos()
        if pos == "s":
            pos = "a"
        related_words_dict[pos].add(lemma.name())
    noun_set = [noun for noun in related_words_dict["n"]]
    for noun in noun_set:
        related_words_dict["n"].add(inflect.engine().plural_noun(noun))
    verb_set = [verb for verb in related_words_dict["v"]]
    for verb in verb_set:
        for conjugated_verbs in CONJUGATED_VERB_LIST:
            if verb in conjugated_verbs:
                for conjugated_verb in conjugated_verbs:
                    related_words_dict["v"].add(conjugated_verb)
    adjective_set = [adjective for adjective in related_words_dict["a"]]
    for adjective in adjective_set:
        try:
            related_words_dict["r"].add(ADJECTIVE_TO_ADVERB[adjective])
        except KeyError:
            pass
    return related_words_dict
项目:abc    作者:daemon    | 项目源码 | 文件源码
def __init__(self, top10k, top100k, nlp, model):
    self.top10k = top10k
    self.top100k = top100k
    self.nlp = nlp
    self.model = model
    self.cache = {}
    self.engine = inflect.engine()
    self.word_pattern = re.compile(r"^\w[\w\.\d]*$")
项目:abc    作者:daemon    | 项目源码 | 文件源码
def pluralize(self, original, target):
    if self.is_plural(original) and not self.is_plural(target):
      try:
        return self.engine.plural(target.text)
      except:
        pass
    return target.text
项目:Penny-Dreadful-Tools    作者:PennyDreadfulMTG    | 项目源码 | 文件源码
def og_description(self):
        if self.archetype_name:
            p = inflect.engine()
            archetype_s = titlecase.titlecase(p.a(self.archetype_name))
        else:
            archetype_s = 'A'
        description = '{archetype_s} deck by {author}'.format(archetype_s=archetype_s, author=self.person.decode('utf-8'))
        return description
项目:Penny-Dreadful-Tools    作者:PennyDreadfulMTG    | 项目源码 | 文件源码
def __init__(self):

        info = tournaments.next_tournament_info()
        self.next_tournament_name = info['next_tournament_name']
        self.next_tournament_time = info['next_tournament_time']
        self.leaderboards_url = url_for('tournament_leaderboards')

        self.tournaments = tournaments.all_series_info()
        p = inflect.engine()
        self.num_tournaments = p.number_to_words(len(self.tournaments))

        self.bugs_rules = rules.bugs(fmt=rules.HTML)
项目:Penny-Dreadful-Tools    作者:PennyDreadfulMTG    | 项目源码 | 文件源码
def day2ordinal(m):
    p = inflect.engine()
    return p.ordinal(int(m.group(1)))
项目:julz_legacy    作者:djsegal    | 项目源码 | 文件源码
def pluralize(self, word):
    if inflect.engine().singular_noun(word): return word
    return inflect.engine().plural(word)
项目:julz_legacy    作者:djsegal    | 项目源码 | 文件源码
def singularize(self, word):
    singularWord = inflect.engine().singular_noun(word)
    if singularWord: return singularWord
    return word
项目:tcex    作者:ThreatConnect-Inc    | 项目源码 | 文件源码
def __init__(self):
        """Initialize class data.

        Setup default values and logging method.
        """
        # init inflect engine
        self.inflect = inflect.engine()

        self._exit_code = 0
        # TODO: replace group_type with dynamic values from API (bcs)
        self.group_types = [
            'Adversary',
            'Campaign',
            'Document',
            'Email',
            'Incident',
            'Signature',
            'Threat'
        ]
        self._indicator_associations_types_data = {}
        self._indicator_types = []
        self._indicator_types_data = {}
        self._max_message_length = 255
        # NOTE: odd issue where args is not updating properly
        self._tc_token = None
        self._tc_token_expires = None

        # Parser
        self._parsed = False
        self.parser = ArgParser()
        self.default_args, unknown = self.parser.parse_known_args()

        # NOTE: odd issue where args is not updating properly
        if self.default_args.tc_token is not None:
            self._tc_token = self.default_args.tc_token
        if self.default_args.tc_token_expires is not None:
            self._tc_token_expires = self.default_args.tc_token_expires

        # logger (must parse args first)
        self.log = self._logger(self.default_args.tc_log_file)

        # Log versions
        self._log_platform()
        self._log_app_version()
        self._log_python_version()
        self._log_tcex_version()
        self._log_tc_proxy()

        # include jobs module
        self._jobs()

        # include playbook module
        self._playbook()

        # include resources module
        self._resources()

        # include utils module
        self._utils()
项目:ttbp    作者:modgethanc    | 项目源码 | 文件源码
def check_init():
    '''
    user handler

    * checks for presence of ttbprc
    * checks for last run version
    '''

    global SETTINGS

    print("\n\n")
    if os.path.exists(os.path.join(os.path.expanduser("~"),".ttbp")):
        print(chatter.say("greet")+", "+config.USER+".\n")

        '''
        ## ttbprc validation
        while not os.path.isfile(config.TTBPRC):
            setup_repair()
        try:
            SETTINGS = json.load(open(config.TTBPRC))
        except ValueError:
            setup_repair()
        '''

        ## ttbp env validation
        if not valid_setup():
            setup_repair()

        ## version checker
        mismatch = build_mismatch()
        if mismatch is not False:
            switch_build(mismatch)
        if not updated():
            update_version()

        ## when ready, enter main program and load core engine
        raw_input("press <enter> to explore your feels.\n\n")
        core.load(SETTINGS)

        return ""
    else:
        return init()
项目:ttbp    作者:modgethanc    | 项目源码 | 文件源码
def init():
    '''
    new user creation

    * introduces user
    * calls setup functinos
    '''

    try:
        raw_input("""
i don't recognize you, stranger. let's make friends.

press <enter> to begin, or <ctrl-c> to get out of here.
        """)
    except KeyboardInterrupt:
        print("\n\nthanks for checking in! i'll always be here.\n\n")
        quit()

    ## record user in source list
    users = open(config.USERFILE, 'a')
    users.write(config.USER+"\n")
    users.close()

    #subprocess.call(['chmod', 'a+w', config.USERFILE])

    ## make .ttbp directory structure
    subprocess.call(["mkdir", config.PATH])
    subprocess.call(["mkdir", config.USER_CONFIG])
    subprocess.call(["mkdir", config.USER_DATA])

    versionFile = os.path.join(config.PATH, "version")
    open(versionFile, "w").write(__version__)

    ## create header file
    header = gen_header()
    headerfile = open(os.path.join(config.USER_CONFIG, "header.txt"), 'w')
    for line in header:
        headerfile.write(line)
    headerfile.close()

    ## copy footer and default stylesheet
    with open(os.path.join(config.USER_CONFIG, 'footer.txt'), 'w') as f:
        f.write(config.DEFAULT_FOOTER)
    with open(os.path.join(config.USER_CONFIG, 'style.css'), 'w') as f:
        f.write(config.DEFAULT_STYLE)

    ## run user-interactive setup and load core engine
    setup()
    core.load(SETTINGS)

    #raw_input("\nyou're all good to go, "+chatter.say("friend")+"! hit <enter> to continue.\n\n")
    return ""
项目:ttbp    作者:modgethanc    | 项目源码 | 文件源码
def check_init():
    '''
    user handler

    * checks for presence of ttbprc
    * checks for last run version
    '''

    global SETTINGS

    print("\n\n")
    if os.path.exists(os.path.join(os.path.expanduser("~"),".ttbp")):
        print(chatter.say("greet")+", "+USER+".\n")

        '''
        ## ttbprc validation
        while not os.path.isfile(TTBPRC):
            setup_repair()
        try:
            SETTINGS = json.load(open(TTBPRC))
        except ValueError:
            setup_repair()
        '''

        ## ttbp env validation
        if not valid_setup():
            setup_repair()

        ## version checker
        mismatch = build_mismatch()
        if mismatch is not False:
            switch_build(mismatch)
        if not updated():
            update_version()

        ## when ready, enter main program and load core engine
        raw_input("press <enter> to explore your feels.\n\n")
        core.load(SETTINGS)

        return ""
    else:
        return init()
项目:threatconnect-developer-docs    作者:ThreatConnect-Inc    | 项目源码 | 文件源码
def __init__(self):
        """Initialize class data.

        Setup default values and logging method.
        """
        # init inflect engine
        self.inflect = inflect.engine()

        self._exit_code = 0
        # TODO: replace group_type with dynamic values from API (bcs)
        self.group_types = [
            'Adversary',
            'Campaign',
            'Document',
            'Email',
            'Incident',
            'Signature',
            'Threat'
        ]
        self._indicator_associations_types_data = {}
        self._indicator_types = []
        self._indicator_types_data = {}
        self._max_message_length = 255
        # NOTE: odd issue where args is not updating properly
        self._tc_token = None
        self._tc_token_expires = None

        # Parser
        self._parsed = False
        self.parser = ArgParser()
        self.default_args, unknown = self.parser.parse_known_args()

        # NOTE: odd issue where args is not updating properly
        if self.default_args.tc_token is not None:
            self._tc_token = self.default_args.tc_token
        if self.default_args.tc_token_expires is not None:
            self._tc_token_expires = self.default_args.tc_token_expires

        # logger (must parse args first)
        self.log = self._logger(self.default_args.tc_log_file)

        # Log versions
        self._log_platform()
        self._log_app_version()
        self._log_python_version()
        self._log_tcex_version()
        self._log_tc_proxy()

        # include jobs module
        self._jobs()

        # include playbook module
        self._playbook()

        # include resources module
        self._resources()

        # include utils module
        self._utils()