def test_construct_integer_cache(self): self.assertNotEqual(id(constructors.construct_integer(1)), id(constructors.construct_integer(-1))) a = constructors.construct_integer(constructors._INTEGER_CACHE_LEFT-1) b = constructors.construct_integer(constructors._INTEGER_CACHE_LEFT-1) self.assertFalse(a is b) a = constructors.construct_integer(constructors._INTEGER_CACHE_RIGHT+1) b = constructors.construct_integer(constructors._INTEGER_CACHE_RIGHT+1) self.assertFalse(a is b) for i in xrange(constructors._INTEGER_CACHE_RIGHT - constructors._INTEGER_CACHE_LEFT+1): self.assertEqual(id(constructors.construct_integer(i)), id(constructors.construct_integer(i)))
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 _construct_coins(value): from the_tale.game import relations as game_relations from the_tale.linguistics.storage import restrictions_storage value = int(value) utg_name = utg_constructors.construct_integer(value) # check from greater amount to zero for record in reversed(game_relations.COINS_AMOUNT.records): if record.minumum <= value: sum_restriction = restrictions_storage.get_restriction( relations.TEMPLATE_RESTRICTION_GROUP.COINS_AMOUNT, record.value).id return (utg_name, [sum_restriction])
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.iteritems(): 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 preprocessed_externals(self): externals = {} for k, (word_form, additional_properties) in self.externals.items(): if isinstance(word_form, int): word_form = utg_constructors.construct_integer(word_form) else: word_form = lexicon_dictionary.DICTIONARY.get_word(word_form) if additional_properties: properties = utg_words.Properties(word_form.properties, *[VERBOSE_TO_PROPERTIES[prop.strip()] for prop in additional_properties.split(',') if prop]) word_form = utg_words.WordForm(word=word_form.word, properties=properties) externals[k] = word_form return externals
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 test_construct_integer_cache(self): self.assertNotEqual(id(constructors.construct_integer(1)), id(constructors.construct_integer(-1))) a = constructors.construct_integer(constructors._INTEGER_CACHE_LEFT - 1) b = constructors.construct_integer(constructors._INTEGER_CACHE_LEFT - 1) self.assertFalse(a is b) a = constructors.construct_integer(constructors._INTEGER_CACHE_RIGHT + 1) b = constructors.construct_integer(constructors._INTEGER_CACHE_RIGHT + 1) self.assertFalse(a is b) for i in range(constructors._INTEGER_CACHE_RIGHT - constructors._INTEGER_CACHE_LEFT + 1): self.assertEqual(id(constructors.construct_integer(i)), id(constructors.construct_integer(i)))
[u'меч', u'варенье', u'чашка', u'дрова'])), ('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,
[u'меч', u'варенье', u'чашка', u'дрова'])), ('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 = (('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,
def expected(value, record): return (utg_constructors.construct_integer(value), [storage.restrictions_storage.get_restriction(linguistics_relations.TEMPLATE_RESTRICTION_GROUP.COINS_AMOUNT, record.value).id])
u'слонами', u'слонах' ], properties=words.Properties(r.ANIMALITY.ANIMATE, r.GENDER.MASCULINE))) #создаем шаблон template1 = templates.Template() template2 = templates.Template() template3 = templates.Template() template1.parse( u'[fairy] [подарил|fairy] [hero|дт] [coins] [монета|coins|вн].', externals=('hero', 'fairy', 'coins')) result1 = template1.substitute(externals={ 'hero': hero, 'fairy': fairy, 'coins': constructors.construct_integer(125) }, dictionary=test_dictionary) template2.parse( u'[fairy] и [eleph] [подарил|мн] [hero|дт] [coins] [монета|coins|вн].', externals=('hero', 'eleph', 'fairy', 'coins')) result2 = template2.substitute(externals={ 'hero': hero, 'eleph': eleph, 'fairy': fairy, 'coins': constructors.construct_integer(125) }, dictionary=test_dictionary) template3.parse(
def _construct_number(value): return (utg_constructors.construct_integer(int(value)), [])
hero = words.WordForm( 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.ANIMATE, r.GENDER.MASCULINE))) npc = words.WordForm( 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.ANIMATE, r.GENDER.FEMININE))) result = template.substitute(externals={ 'hero': hero, 'npc': npc, 'games': constructors.construct_integer(125) }, dictionary=test_dictionary) print(result)
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 монет.')