Python:用随机选择替换多个单词
我有一个带有特殊标记的单词的短语,我想替换它。这些单词与字典中的一个键匹配,字典中有一个我想随机选择替换的单词列表 我想知道是否有更好的方法来做这件事,或者我所做的似乎是一个有效的方法?我有一种感觉,也许有一种更聪明的方法可以使用Python:用随机选择替换多个单词,python,python-2.7,dictionary,random,Python,Python 2.7,Dictionary,Random,我有一个带有特殊标记的单词的短语,我想替换它。这些单词与字典中的一个键匹配,字典中有一个我想随机选择替换的单词列表 我想知道是否有更好的方法来做这件事,或者我所做的似乎是一个有效的方法?我有一种感觉,也许有一种更聪明的方法可以使用lambda,但我不确定 希望代码能自己解释 import random words = {"fruit":["apples", "bananas", "oranges"], "veggies":["broccoli", "corn", "cucu
lambda
,但我不确定
希望代码能自己解释
import random
words = {"fruit":["apples", "bananas", "oranges"],
"veggies":["broccoli", "corn", "cucumbers"]}
txt = "I'm not in a mood for [veggies], I rather have [fruit], and [fruit]."
for key in words:
target_word = "[{0}]".format(key)
while target_word in txt:
txt = txt.replace(target_word, random.choice(words[key]), 1)
运行几次将随机输出:
我不想吃玉米,我宁愿吃香蕉和苹果
我没心情吃花椰菜,我宁愿吃桔子和香蕉
我没心情吃黄瓜,我宁愿吃苹果和桔子
……等等
我应该提到的是,在
单词中可以有任意数量的键,在文本中可以有任意数量的标记单词。这可以是一种方法:
import random
words = {"fruit":["apples", "bananas", "oranges"],
"veggies":["broccoli", "corn", "cucumbers"]}
txt = "I'm not in a mood for [veggies], I rather have [fruit]."
txt = txt.replace('[veggies]', random.choice(words['veggies'])).replace('[fruit]', random.choice(words['fruit']))
我是用re.findall
然后str.replace
完成的,但我觉得它也不比你的好多少
import random
words = {"fruit":["apples", "bananas", "oranges"],
"veggies":["broccoli", "corn", "cucumbers"]}
txt = "I'm not in a mood for [veggies], I rather have [fruit], and [fruit]."
found = re.findall('\[\w+\]', txt)
for m in found:
txt = txt.replace(m, random.choice(words.get(m.strip('[]'), [m])), 1)
re.sub
还接受可调用的asrepl
参数:
In [19]: import random, re
...:
...: words = {"fruit":["apples", "bananas", "oranges"],
...: "veggies":["broccoli", "corn", "cucumbers"]}
...:
...: txt = "I'm not in a mood for [veggies], I rather have [fruit], and [fruit]."
...:
In [20]: regex = re.compile(r'\[({})\]'.format('|'.join(words)))
In [21]: regex.pattern
Out[21]: '\\[(fruit|veggies)\\]'
In [22]: regex.sub(lambda match: random.choice(words[match.group(1)]), txt)
Out[22]: "I'm not in a mood for broccoli, I rather have bananas, and apples."
In [23]: regex.sub(lambda match: random.choice(words[match.group(1)]), txt)
Out[23]: "I'm not in a mood for corn, I rather have oranges, and oranges."
我认为这是对Python Zen的反对。然而,这将失去活力。该示例从字典键中选择要替换的单词,您的答案将其硬编码为水果和蔬菜。感谢您的努力,但正如Hannu所说,这是硬编码的。我编辑了我的问题来澄清这一点。谢谢,尽管我喜欢你的想法,但我还是有点同意Python Zen。也许最好还是坚持我现在拥有的。@GreenCell是的,但是re.sub速度更快。如果速度真的很重要的话,这是值得的。