3 回答
TA贡献1852条经验 获得超7个赞
您正在寻找具有回调功能的re.sub:
words = {
'person': ['you', 'me'],
'how': ['fine', 'stupid'],
'where': ['away', 'out']
}
import re, random
def 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
基本上,您可以在此之上构建自己的“模板引擎”。
TA贡献1821条经验 获得超4个赞
您可以使用该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你可以从方括号来卷曲那些切换。
TA贡献1812条经验 获得超5个赞
如果使用花括号而不是括号,则您的字符串可以用作字符串格式模板。您可以使用itertools.product用很多替代来填充它:
import itertools as IT
text = "{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(']','}')
添加回答
举报