def compress(self, data_list): fields = get_fields(self.word_type) keys = {key: i for i, key in enumerate(sorted(fields.keys()))} word_forms = [ data_list[keys['%s_%d' % (WORD_FIELD_PREFIX, i)]] for i in range(len(utg_data.INVERTED_WORDS_CACHES[self.word_type])) ] properties = utg_words.Properties() for static_property, required in self.word_type.properties.items(): value = data_list[keys['%s_%s' % (WORD_FIELD_PREFIX, static_property.__name__)]] if not value: continue properties = utg_words.Properties(properties, value) word = utg_words.Word(type=self.word_type, forms=word_forms, properties=properties) word.autofill_missed_forms() return word
def get_name(self, race, gender): name_forms = self._get_name(race, gender).get_forms_for(gender=gender.pynames_id, language=self.language) name_forms += ['']*6 name = utg_words.Word(type=utg_relations.WORD_TYPE.NOUN, forms=name_forms, properties=utg_words.Properties(utg_relations.ANIMALITY.ANIMATE, gender.utg_id)) name.autofill_missed_forms() return name
def test_construct_integer(self): singular_properties = words.Properties(r.NUMBER.SINGULAR, r.INTEGER_FORM.SINGULAR) singular_plural_properties = words.Properties(r.NUMBER.PLURAL, r.INTEGER_FORM.SINGULAR) dual_properties = words.Properties(r.NUMBER.PLURAL, r.INTEGER_FORM.DUAL) composite_dual_properties = words.Properties( r.NUMBER.PLURAL, r.INTEGER_FORM.COMPOSITE_DUAL) plural_properties = words.Properties(r.NUMBER.PLURAL, r.INTEGER_FORM.PLURAL) mil_bil_properties = words.Properties(r.NUMBER.PLURAL, r.INTEGER_FORM.MIL_BIL) tests = { 1: singular_properties, 2: dual_properties, 3: dual_properties, 4: dual_properties, 5: plural_properties, 10: plural_properties, 11: plural_properties, 12: plural_properties, 13: plural_properties, 14: plural_properties, 15: plural_properties, 24: composite_dual_properties, 25: plural_properties, 1001: singular_plural_properties, 1002: composite_dual_properties, 1003: composite_dual_properties, 1004: composite_dual_properties, 1005: plural_properties, 1010: plural_properties, 1011: plural_properties, 1012: plural_properties, 1013: plural_properties, 1014: plural_properties, 1015: plural_properties, 1024: composite_dual_properties, 1025: plural_properties, 1000000: mil_bil_properties, 1000000000: mil_bil_properties } for number, properties in tests.items(): word = words.Word(type=r.WORD_TYPE.INTEGER, forms=['%d' % number], properties=properties) integer_form = constructors.construct_integer(number) self.assertEqual(integer_form.word, word) self.assertEqual(integer_form.properties, word.properties)
def test_init(self): forms = [ 'x%d' % i for i in range(len(data.WORDS_CACHES[r.WORD_TYPE.VERB])) ] word = words.Word(type=r.WORD_TYPE.VERB, forms=forms, properties=words.Properties(r.CASE.DATIVE, r.TIME.FUTURE)) self.assertTrue(word.type.is_VERB) self.assertEqual(word.forms, forms) self.assertEqual(word.properties, words.Properties(r.CASE.DATIVE, r.TIME.FUTURE))
def test_starts_with_consonant_cluster(self): word = words.Word(type=r.WORD_TYPE.NOUN, forms=[ 'сон', 'сна', 'сну', 'сон', 'сном', 'сне', 'сны', 'снов', 'снам', 'сны', 'снами', 'снах', 'сны', 'снов', 'снам', 'сны', 'снами', 'снах' ], properties=words.Properties(r.GENDER.MASCULINE, r.ANIMALITY.INANIMATE)) form = words.WordForm(word=word, properties=words.Properties( r.CASE.NOMINATIVE)) # сон self.assertFalse(form.starts_with_consonant_cluster) form = words.WordForm(word=word, properties=words.Properties( r.CASE.DATIVE)) # сну self.assertTrue(form.starts_with_consonant_cluster)
def test_autofill_missed_forms(self): word = words.Word(type=r.WORD_TYPE.NOUN, forms=[ 'сон', 'сна', '', 'сон', 'сном', 'сне', 'сны', 'снов', 'снам', '', 'снами', 'снах', 'сны', '', '', '', 'снами', '' ], properties=words.Properties(r.GENDER.MASCULINE, r.ANIMALITY.INANIMATE)) word.autofill_missed_forms() # print u', '.join(word.forms[:6]) # print u', '.join(word.forms[6:12]) # print u', '.join(word.forms[12:]) self.assertEqual(word.forms, [ 'сон', 'сна', 'снам', 'сон', 'сном', 'сне', 'сны', 'снов', 'снам', 'сон', 'снами', 'снах', 'сны', 'снов', 'снам', 'сны', 'снами', 'снах' ])
def test_has_fluent_vowel(self): word = words.Word.create_test_word(type=r.WORD_TYPE.NOUN) word.forms = ['абракадубр'] * len(word.forms) self.assertFalse(word.has_fluent_vowel) word = words.Word.create_test_word(type=r.WORD_TYPE.NOUN) word.forms = ['абракадубр'] + [ 'абракадубр' + random.choice(list(data.VOWELS)) for i in range(len(word.forms) - 1) ] self.assertFalse(word.has_fluent_vowel) word = words.Word(type=r.WORD_TYPE.NOUN, forms=[ 'сон', 'сна', 'сну', 'сон', 'сном', 'сне', 'сны', 'снов', 'снам', 'сны', 'снами', 'снах', 'сны', 'снов', 'снам', 'сны', 'снами', 'снах' ], properties=words.Properties(r.GENDER.MASCULINE, r.ANIMALITY.INANIMATE)) self.assertTrue(word.has_fluent_vowel)
def _construct_integer(number): form = str(number) number = abs(number) if number in (1000000, 1000000000): properties = INTEGER_PROPERTIES.IS_KKK.properties elif number == 1: properties = INTEGER_PROPERTIES.IS_1.properties elif number in (2, 3, 4): properties = INTEGER_PROPERTIES.IS_234.properties elif 10 <= number % 100 <= 19: properties = INTEGER_PROPERTIES.IS_10_19.properties elif number % 10 == 1: properties = INTEGER_PROPERTIES.IS_END_BY_1.properties elif 2 <= number % 10 <= 4: properties = INTEGER_PROPERTIES.IS_MOD_234.properties else: properties = INTEGER_PROPERTIES.IS_OTHER.properties return words.WordForm( words.Word(type=r.WORD_TYPE.INTEGER, forms=[form], properties=properties))
def test_full_usage(self): # описываем существительное для словаря coins_word = words.Word( type=r.WORD_TYPE.NOUN, forms=[ 'монета', 'монеты', 'монете', 'монету', 'монетой', 'монете', # единственнео число 'монеты', 'монет', 'монетам', 'монеты', 'монетами', 'монетах', # множественное число 'монеты', 'монет', 'монетам', 'монеты', 'монетами', 'монетах' ], # счётное число (заполнено для пример, может быть заполнено методом autofill_missed_forms) properties=words.Properties( r.ANIMALITY.INANIMATE, r.GENDER.FEMININE)) # свойства: неодушевлённое, женский род # описываем глагол для словаря action_word = words.Word( type=r.WORD_TYPE.VERB, # описываем только нужны нам формы слова (порядок важен и определён в utg.data.WORDS_CACHES[r.WORD_TYPE.VERB]) forms=['подарить', 'подарил', 'подарило', 'подарила', 'подарили'] + [''] * (len(data.WORDS_CACHES[r.WORD_TYPE.VERB]) - 5), properties=words.Properties(r.ASPECT.PERFECTIVE, r.VOICE.DIRECT)) action_word.autofill_missed_forms( ) # заполняем пропущенные формы на основе введённых (выбираются наиболее близкие) # создаём словарь для использования в шаблонах test_dictionary = dictionary.Dictionary( words=[coins_word, action_word]) # создаём шаблон template = templates.Template() # externals — внешние переменные, не обязаны быть в словаре template.parse( '[Npc] [подарил|npc] [hero|дт] [coins] [монета|coins|вн].', externals=('hero', 'npc', 'coins')) # описываем внешние переменные hero = words.WordForm( words.Word(type=r.WORD_TYPE.NOUN, forms=[ 'герой', 'героя', 'герою', 'героя', 'героем', 'герое', 'герои', 'героев', 'героям', 'героев', 'героями', 'героях', 'герои', 'героев', 'героям', 'героев', 'героями', 'героях' ], properties=words.Properties(r.ANIMALITY.ANIMATE, r.GENDER.MASCULINE))) npc = words.WordForm( words.Word(type=r.WORD_TYPE.NOUN, forms=[ 'русалка', 'русалки', 'русалке', 'русалку', 'русалкой', 'русалке', 'русалки', 'русалок', 'русалкам', 'русалок', 'русалками', 'русалках', 'русалки', 'русалок', 'русалкам', 'русалок', 'русалками', 'русалках' ], properties=words.Properties(r.ANIMALITY.ANIMATE, r.GENDER.FEMININE))) # осуществляем подстановку result = template.substitute(externals={ 'hero': hero, 'npc': npc, 'coins': constructors.construct_integer(125) }, dictionary=test_dictionary) self.assertEqual(result, 'Русалка подарила герою 125 монет.')
def utg_name_form(self): return utg_words.WordForm( utg_words.Word(type=WORD_TYPE.TEXT, forms=(self.date.verbose_full(), )))
s([u'любой текст'], [u'текст текст текст'], [u'какой-то текст'])), ('MODIFIER', 6, u'модификатор города', WORD_TYPE.NOUN, s([u'форт', u'захолустье', u'святыня', (u'мемориал', u'мн')], [u'замок', u'пристанище', u'земля', (u'колония', u'мн')])), ('RACE', 7, u'раса', WORD_TYPE.NOUN, s([u'человек', u'эльф', u'орк', u'гоблин', u'дварф'], [u'человек', u'эльф', u'орк', u'гоблин', u'дварф'], [u'человек', u'эльф', u'орк', u'гоблин', u'дварф']))) _construct_utg_name_form = lambda v: (v.utg_name_form, v.linguistics_restrictions()) _construct_number = lambda v: (utg_constructors.construct_integer(int(v)), []) _construct_text = lambda v: (utg_words.WordForm( utg_words.Word(type=WORD_TYPE.TEXT, forms=(v, ))), []) class VARIABLE_TYPE(DjangoEnum): verificator = Column(unique=False, no_index=True) constructor = Column(unique=False, no_index=True) restrictions = Column(unique=False, no_index=True) records = (('HERO', 0, u'герой', VARIABLE_VERIFICATOR.PERSON, _construct_utg_name_form, (relations.TEMPLATE_RESTRICTION_GROUP.GENDER, relations.TEMPLATE_RESTRICTION_GROUP.RACE, relations.TEMPLATE_RESTRICTION_GROUP.HABIT_HONOR, relations.TEMPLATE_RESTRICTION_GROUP.HABIT_PEACEFULNESS, relations.TEMPLATE_RESTRICTION_GROUP.ARCHETYPE, relations.TEMPLATE_RESTRICTION_GROUP.TERRAIN,
def test_preposition_consonants(self): pre_1 = self._create_preposition(['под', 'подо', 'подо']) pre_2 = self._create_preposition(['за', 'за', 'за']) pre_3 = self._create_preposition(['в', 'во', 'во']) pre_4 = self._create_preposition(['с', 'со', 'со']) master_word_1 = words.Word( type=r.WORD_TYPE.NOUN, forms=[ 'сон', 'сна', 'сну', 'сон', 'сном', 'сне', 'сны', 'снов', 'снам', 'сны', 'снами', 'снах', 'сны', 'снов', 'снам', 'сны', 'снами', 'снах' ], properties=words.Properties(r.GENDER.MASCULINE, r.ANIMALITY.INANIMATE)) master_word_2 = words.Word( type=r.WORD_TYPE.NOUN, forms=[ 'сновидение', 'сновидения', 'сновидению', 'сновидение', 'сновидением', 'сновидении', 'сновидения', 'сновидений', 'сновидениям', 'сновидения', 'сновидениями', 'сновидениях', 'сновидения', 'сновидений', 'сновидениям', 'сновидения', 'сновидениями', 'сновидениях' ], properties=words.Properties(r.GENDER.NEUTER, r.ANIMALITY.INANIMATE)) master_word_3 = words.Word( type=r.WORD_TYPE.NOUN, forms=[ 'власть', 'власти', 'власти', 'власть', 'властью', 'власти', '', '', '', '', '', '', '', '', '', '', '', '' ], properties=words.Properties(r.GENDER.MASCULINE, r.ANIMALITY.INANIMATE, r.NUMBER.SINGULAR)) slave_properties = words.Properties( random.choice(r.PREPOSITION_FORM.records)) master_form_1 = words.WordForm(word=master_word_1, properties=words.Properties( r.CASE.NOMINATIVE)) # сон master_form_2 = words.WordForm(word=master_word_1, properties=words.Properties( r.CASE.DATIVE)) # сну master_form_3 = words.WordForm(word=master_word_2) # сновидение master_form_4 = words.WordForm(word=master_word_3) # власть tests = { (pre_1, master_form_1): slave_properties, # под сон (pre_1, master_form_2): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # подо сну (pre_1, master_form_3): slave_properties, # под сновидение (pre_1, master_form_4): slave_properties, # под власть (pre_2, master_form_1): slave_properties, # за сон (pre_2, master_form_2): slave_properties, # за сну (pre_2, master_form_3): slave_properties, # за сновидение (pre_2, master_form_4): slave_properties, # за власть (pre_3, master_form_1): slave_properties, # в сон (pre_3, master_form_2): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # во сну (pre_3, master_form_3): slave_properties, # в сновидение (pre_3, master_form_4): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # во власть (pre_4, master_form_1): slave_properties, # с сон (pre_4, master_form_2): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # со сну (pre_4, master_form_3): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # со сновидение (pre_4, master_form_4): slave_properties } # с власть for (pre, master_form), result_properties in tests.items(): self.assertEqual( transformators._preposition_any(properties=slave_properties, slave_word=pre, master_form=master_form), result_properties)
def test_preposition_vovels(self): pre_1 = self._create_preposition(['о', 'об', 'обо']) pre_2 = self._create_preposition(['у', 'у', 'у']) master_word_1 = words.Word( type=r.WORD_TYPE.NOUN, forms=[ 'ужин', 'ужина', 'ужину', 'ужин', 'ужином', 'ужине', 'ужины', 'ужинов', 'ужинам', 'ужины', 'ужинами', 'ужинах', 'ужины', 'ужинов', 'ужинам', 'ужины', 'ужинами', 'ужинах' ], properties=words.Properties(r.GENDER.MASCULINE, r.ANIMALITY.INANIMATE)) master_word_2 = words.Word( type=r.WORD_TYPE.NOUN, forms=[ 'юрист', 'юриста', 'юристу', 'юриста', 'юристом', 'юристе', 'юристы', 'юристов', 'юристам', 'юристов', 'юристами', 'юристах', 'юристы', 'юристов', 'юристам', 'юристов', 'юристами', 'юристах' ], properties=words.Properties(r.GENDER.NEUTER, r.ANIMALITY.INANIMATE)) master_word_3 = words.Word( type=r.WORD_TYPE.PRONOUN, forms=[ 'я', 'я', 'я', 'меня', 'меня', 'меня', 'мне', 'мне', 'мне', 'меня', 'меня', 'меня', 'мной', 'мной', 'мной', 'мне', 'мне', 'мне', 'мы', 'нас', 'нам', 'нас', 'нами', 'нас', 'я', 'я', 'я', 'меня', 'меня', 'меня', 'мне', 'мне', 'мне', 'меня', 'меня', 'меня', 'мной', 'мной', 'мной', 'мне', 'мне', 'мне', 'мы', 'нас', 'нам', 'нас', 'нами', 'нас' ], properties=words.Properties(r.PRONOUN_CATEGORY.PERSONAL)) slave_properties = words.Properties( random.choice(r.PREPOSITION_FORM.records)) master_form_1 = words.WordForm(word=master_word_1, properties=words.Properties( r.CASE.NOMINATIVE)) # ужин master_form_2 = words.WordForm(word=master_word_1, properties=words.Properties( r.CASE.DATIVE)) # ужину master_form_3 = words.WordForm(word=master_word_2) # юрист master_form_4 = words.WordForm(word=master_word_3) # я master_form_5 = words.WordForm(word=master_word_3, properties=words.Properties( r.CASE.DATIVE)) # мне self.assertEqual(master_form_5.form, 'мне') tests = { (pre_1, master_form_1): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # об ужин (pre_1, master_form_2): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # об ужину (pre_1, master_form_3): slave_properties, # о юрист (pre_1, master_form_4): slave_properties, # о я (pre_1, master_form_5): words.Properties(r.PREPOSITION_FORM.SPECIAL), # обо мне (pre_2, master_form_1): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # у ужин (pre_2, master_form_2): words.Properties(r.PREPOSITION_FORM.ALTERNATIVE), # у ужину (pre_2, master_form_3): slave_properties, # у юрист (pre_2, master_form_4): slave_properties, # у я (pre_2, master_form_5): slave_properties, # у мне } for (pre, master_form), result_properties in tests.items(): self.assertEqual( transformators._preposition_any(properties=slave_properties, slave_word=pre, master_form=master_form), result_properties)
from utg import constructors # описываем существительное для словаря coins_word = words.Word( type=r.WORD_TYPE.NOUN, forms=[ u'монета', u'монеты', u'монете', u'монету', u'монетой', u'монете', # единственнео число u'монеты', u'монет', u'монетам', u'монеты', u'монетами', u'монетах', # множественное число u'монеты', u'монет', u'монетам', u'монеты', u'монетами', u'монетах' ], # счётное число (заполнено для пример, может быть заполнено методом autofill_missed_forms) properties=words.Properties( r.ANIMALITY.INANIMATE, r.GENDER.FEMININE)) # свойства: неодушевлённое, женский род # описываем глагол для словаря action_word = words.Word(
# coding: utf-8 from utg import relations as r from utg import logic from utg import data from utg import dictionary from utg import words from utg import templates from utg import constructors games_word = words.Word(type=r.WORD_TYPE.NOUN, forms=[ u'игра', u'игры', u'игре', u'игру', u'игрой', u'игре', u'игры', u'игр', u'играми', u'игры', u'играми', u'играх', u'игры', u'игр', u'играм', u'игры', u'играми', u'играх' ], properties=words.Properties(r.ANIMALITY.INANIMATE, r.GENDER.FEMININE)) action_word = words.Word( type=r.WORD_TYPE.VERB, forms=[u'дать', u'дал', u'дало', u'дала', u'дали'] + [u''] * (len(data.WORDS_CACHES[r.WORD_TYPE.VERB]) - 5), properties=words.Properties(r.ASPECT.PERFECTIVE, r.VOICE.DIRECT)) action_word.autofill_missed_forms() test_dictionary = dictionary.Dictionary(words=[games_word, action_word]) template = templates.Template() template.parse(u'[Npc] [дал|npc] [hero|дт] [games] [игра|games|вн].',
def _create_preposition(self, forms): return words.Word(r.WORD_TYPE.PREPOSITION, forms=forms, properties=words.Properties())
('TEXT', 5, u'любой текст', WORD_TYPE.TEXT, s([u'любой текст'], [u'текст текст текст'], [u'какой-то текст'])), ('MODIFIER', 6, u'модификатор города', WORD_TYPE.NOUN, s([u'форт', u'захолустье', u'святыня', (u'мемориал', u'мн')], [u'замок', u'пристанище', u'земля', (u'колония', u'мн')])), ('RACE', 7, u'раса', WORD_TYPE.NOUN, s([u'человек', u'эльф', u'орк', u'гоблин', u'дварф'], [u'человек', u'эльф', u'орк', u'гоблин', u'дварф'], [u'человек', u'эльф', u'орк', u'гоблин', u'дварф'])) ) _construct_utg_name_form = lambda v: (v.utg_name_form, v.linguistics_restrictions()) _construct_number = lambda v: (utg_constructors.construct_integer(int(v)), []) _construct_text = lambda v: (utg_words.WordForm(utg_words.Word(type=WORD_TYPE.TEXT, forms=(v,))), []) class VARIABLE_TYPE(DjangoEnum): verificator = Column(unique=False, no_index=True) constructor = Column(unique=False, no_index=True) restrictions = Column(unique=False, no_index=True) records = ( ('NUMBER', 1, u'число', VARIABLE_VERIFICATOR.NUMBER, _construct_number, ()), ('PLACE', 2, u'город', VARIABLE_VERIFICATOR.PLACE, _construct_utg_name_form, (relations.TEMPLATE_RESTRICTION_GROUP.CITY_MODIFIER, relations.TEMPLATE_RESTRICTION_GROUP.HABIT_HONOR, relations.TEMPLATE_RESTRICTION_GROUP.HABIT_PEACEFULNESS, relations.TEMPLATE_RESTRICTION_GROUP.TERRAIN, relations.TEMPLATE_RESTRICTION_GROUP.META_TERRAIN, relations.TEMPLATE_RESTRICTION_GROUP.META_HEIGHT, relations.TEMPLATE_RESTRICTION_GROUP.META_VEGETATION,
def _construct_text(value): return (utg_words.WordForm( utg_words.Word(type=WORD_TYPE.TEXT, forms=(value, ))), [])