2

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

"The weather today is [weather_state]."

并且能够做一些事情,比如在 [brackets] 中查找所有标记,然后将它们交换为字典或列表中的随机对应物,给我留下:

"The weather today is warm."
"The weather today is bad."

或者

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

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

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

我真的不知道从哪里开始,或者这甚至是使用标记化或标记模块的最佳解决方案。任何能指出我正确方向的提示都非常感谢!

编辑:只是为了澄清,我真的不需要使用方括号,任何非标准字符都可以。

4

3 回答 3

4

您正在寻找带有回调函数的 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

基本上,您可以在此基础上构建自己的“模板引擎”。

于 2013-05-16T09:38:00.720 回答
2

您可以使用该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."
>>>

当然,这种方法只有在您可以从方括号切换到大括号时才有效。

于 2013-05-16T09:35:28.200 回答
0

如果您使用大括号而不是方括号,那么您的字符串可以用作字符串格式化模板您可以使用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(']','}')
于 2013-05-16T09:41:31.947 回答