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)))
python类engine()的实例源码
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
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)
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)
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)
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],
)
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)
def make_entity_name(field_name):
inflector = inflect.engine()
return (inflector.singular_noun(field_name) or field_name).title()
def inflector():
global __inflector
if __inflector is None:
__inflector = inflect.engine()
return __inflector
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()
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'
)
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)
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)
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)
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 = []
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)
def create_inflect_engine(self):
if self.noinflect:
return _DummyInflectEngine()
else:
import inflect
return inflect.engine()
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
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
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
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
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
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
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]*$")
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
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
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)
def day2ordinal(m):
p = inflect.engine()
return p.ordinal(int(m.group(1)))