2016-11-15 41 views
1

我有一個帶有一些我想替換的特殊標記單詞的短語。這些詞匹配字典中的一個關鍵字,該關鍵字具有我想隨機選擇替換的單詞列表。Python:用隨機選擇替換多個單詞

我想知道是否有更好的方式去做這件事,或者是我看起來像一個有效的方法?我有一種感覺,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任意數字鍵,以及任意數量的文本標記的話。

回答

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禪。

+0

謝謝,雖然我喜歡你所提出的,但我確實有點贊同Python Zen。也許最好是堅持我所擁有的東西。 –

+0

@GreenCell是的,但re.sub更快。如果速度真的很重要,它確實值得。 – robyschek

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

然而,這會失去活力。該示例選擇要從字典鍵中替換的單詞,您的答案將它們編碼爲水果和蔬菜。 – Hannu

+0

感謝您的努力,但像Hannu說的,這是硬編碼。我編輯了我的問題來澄清這一點。 –

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) 
+0

是非常相似,但使用正則表達式的好主意! –