【问题标题】:Python: Replacing multiple words with a random choicePython:用随机选择替换多个单词
【发布时间】: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


    【解决方案1】:

    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 相悖。

    【讨论】:

    • 谢谢,虽然我喜欢你的想法,但我确实有点同意 Python Zen。也许最好还是坚持我当时所拥有的。
    • @GreenCell 是的,但 re.sub 更快。如果速度真的很重要,那就值得了。
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      这可能是一种方法:

      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']))
      

      【讨论】:

      • 然而,这会失去活力。该示例从字典键中选择要替换的单词,您的答案将它们硬编码为水果和蔬菜。
      • 感谢您的努力,但正如 Hannu 所说,这是硬编码的。我编辑了我的问题以澄清这一点。
      猜你喜欢
      • 2019-04-24
      • 1970-01-01
      • 2018-03-30
      • 2012-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多