猿问

Python-标记化,替换单词

我正在尝试创建带有随机单词的句子之类的东西。具体来说,我会有类似的东西:


"The weather today is [weather_state]."

并能够执行类似在[方括号]中找到所有标记的操作,然后将它们与字典或列表中的随机对应物交换,从而给我留下了:


"The weather today is warm."

"The weather today is bad."

或者


"The weather today is mildly suiting for my old bones."

请记住,[括号]标记的位置并不总是在同一位置,并且在我的字符串中将有多个括号中的标记,例如:


"[person] is feeling really [how] today, so he's not going [where]."

我真的不知道从哪里开始,或者这甚至是使用令牌化或令牌模块的最佳解决方案。任何暗示我朝正确方向的提示都将不胜感激!


慕森卡
浏览 195回答 3
3回答

慕姐4208626

您正在寻找具有回调功能的re.sub:words = {    'person': ['you', 'me'],    'how': ['fine', 'stupid'],    'where': ['away', 'out']}import re, randomdef random_str(m):    return random.choice(words[m.group(1)])text = "[person] is feeling really [how] today, so he's not going [where]."print re.sub(r'\[(.+?)\]', random_str, text)#me is feeling really stupid today, so he's not going away.   注意,与format方法不同,这允许对占位符进行更复杂的处理,例如[person:upper] got $[amount if amount else 0] etc基本上,您可以在此之上构建自己的“模板引擎”。

收到一只叮咚

您可以使用该format方法。>>> a = 'The weather today is {weather_state}.'>>> a.format(weather_state = 'awesome')'The weather today is awesome.'>>>还:>>> b = '{person} is feeling really {how} today, so he\'s not going {where}.'>>> b.format(person = 'Alegen', how = 'wacky', where = 'to work')"Alegen is feeling really wacky today, so he's not going to work.">>>当然,这种方法只适用IF你可以从方括号来卷曲那些切换。

ABOUTYOU

如果使用花括号而不是括号,则您的字符串可以用作字符串格式模板。您可以使用itertools.product用很多替代来填充它:import itertools as ITtext = "{person} is feeling really {how} today, so he's not going {where}."persons = ['Buster', 'Arthur']hows = ['hungry', 'sleepy']wheres = ['camping', 'biking']for person, how, where in IT.product(persons, hows, wheres):    print(text.format(person=person, how=how, where=where))产量Buster is feeling really hungry today, so he's not going camping.Buster is feeling really hungry today, so he's not going biking.Buster is feeling really sleepy today, so he's not going camping.Buster is feeling really sleepy today, so he's not going biking.Arthur is feeling really hungry today, so he's not going camping.Arthur is feeling really hungry today, so he's not going biking.Arthur is feeling really sleepy today, so he's not going camping.Arthur is feeling really sleepy today, so he's not going biking.要生成随机句子,可以使用random.choice:for i in range(5):    person = random.choice(persons)    how = random.choice(hows)    where = random.choice(wheres)    print(text.format(person=person, how=how, where=where))如果必须使用方括号并且格式中没有大括号,则可以将大括号替换为大括号,然后按上述步骤操作:text = "[person] is feeling really [how] today, so he's not going [where]."text = text.replace('[','{').replace(']','}')
随时随地看视频慕课网APP

相关分类

Python
我要回答