gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:33:29 24 4
gpt4 key购买 nike

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

我想知道是否有更好的方法可以做到这一点,或者我所采用的方法似乎是有效的方法?我有一种感觉,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)

运行几次会随机输出:

I'm not in a mood for corn, I rather have bananas, and apples.

I'm not in a mood for broccoli, I rather have oranges, and bananas.

I'm not in a mood for cucumbers, I rather have apples, and oranges.

..and so on..

我应该提到,单词中可以有任意数量的键,并且文本中可以有任意数量的标记单词。

最佳答案

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:用随机选择替换多个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40603973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com