python类engine()的实例源码

import_magic_cards.py 文件源码 项目:django-magic-cards 作者: pbaranay 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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)))
entity_relationship_diagram.py 文件源码 项目:pyagram 作者: hideshi 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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_local.py 文件源码 项目:tcex 作者: ThreatConnect-Inc 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
resources.py 文件源码 项目:beckett 作者: phalt 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
cli.py 文件源码 项目:restful-api-guidelines-linter 作者: hjacobs 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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)
validate_config.py 文件源码 项目:open-syllabus-project 作者: davidmcclure 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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],
        )
twelve_days.py 文件源码 项目:exercism-python 作者: amalshehu 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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
tcex_local.py 文件源码 项目:threatconnect-developer-docs 作者: ThreatConnect-Inc 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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)
middleware.py 文件源码 项目:mutant 作者: peterdemin 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def make_entity_name(field_name):
        inflector = inflect.engine()
        return (inflector.singular_noun(field_name) or field_name).title()
generator.py 文件源码 项目:mutant 作者: peterdemin 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def inflector():
    global __inflector
    if __inflector is None:
        __inflector = inflect.engine()
    return __inflector
add_error_features.py 文件源码 项目:smt-for-gec 作者: cnap 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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()
handle.py 文件源码 项目:teach-me-aws-stepfunctions 作者: OsamaJBR 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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'
    )
fcts.py 文件源码 项目:nanosat-control 作者: ceyzeriat 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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)
fcts.py 文件源码 项目:nanosat-control 作者: ceyzeriat 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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)
_core.py 文件源码 项目:nanosat-control 作者: ceyzeriat 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)
_core.py 文件源码 项目:nanosat-control 作者: ceyzeriat 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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)
Integer_Combination.py 文件源码 项目:Entity-Triple-Entity-Extraction 作者: shubham0420 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
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 = []
startup.py 文件源码 项目:spikes 作者: mozilla 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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)
codegen.py 文件源码 项目:sqlacodegen 作者: agronholm 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def create_inflect_engine(self):
        if self.noinflect:
            return _DummyInflectEngine()
        else:
            import inflect
            return inflect.engine()
ttbp.py 文件源码 项目:ttbp 作者: modgethanc 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
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.py 文件源码 项目:ttbp 作者: modgethanc 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
__init__.py 文件源码 项目:Canella-CMS 作者: mush42 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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
wordnet_server.py 文件源码 项目:brainforks 作者: minervax 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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.py 文件源码 项目:word_forms 作者: gutfeeling 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
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.py 文件源码 项目:word_forms 作者: gutfeeling 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
__main__.py 文件源码 项目:abc 作者: daemon 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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]*$")
__main__.py 文件源码 项目:abc 作者: daemon 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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
deck.py 文件源码 项目:Penny-Dreadful-Tools 作者: PennyDreadfulMTG 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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
tournaments.py 文件源码 项目:Penny-Dreadful-Tools 作者: PennyDreadfulMTG 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
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)
dtutil.py 文件源码 项目:Penny-Dreadful-Tools 作者: PennyDreadfulMTG 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def day2ordinal(m):
    p = inflect.engine()
    return p.ordinal(int(m.group(1)))


问题


面经


文章

微信
公众号

扫码关注公众号