【发布时间】:2016-11-15 07:07:09
【问题描述】:
我有一个带有一些特殊标记词的短语,我想替换它们。这些单词与字典中的一个键匹配,字典中有一个我想随机选择替换的单词列表。
我想知道是否有更好的方法来做到这一点,或者我认为这是一种有效的方法?我觉得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)
运行几次会随机输出:
我没心情吃玉米,我更喜欢香蕉和苹果。
我没心情吃西兰花,我更喜欢橙子和香蕉。
我没心情吃黄瓜,我更喜欢苹果和橙子。
..等等..
我应该提到,words 中可以有任意数量的键,文本中可以有任意数量的标记词。
【问题讨论】:
标签: python python-2.7 dictionary random