Python:用随机选择替换多个单词

时间:2016-11-15 07:07:10

标签: python python-2.7 dictionary random

我有一个短语,其中包含一些我要替换的特殊标记词。这些单词匹配字典中的一个键,该字典包含我想要随机选择替换的单词列表。

我想知道是否有更好的方法可以做到这一点,或者我认为这是一种有效的方法?我觉得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中可以有任意数量的键,以及文本中任意数量的标记词。

3 个答案:

答案 0 :(得分:2)

re.sub也接受可调用的repl参数:

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。

答案 1 :(得分:1)

我是使用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)

答案 2 :(得分:-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']))