使用random.sample用字典中的值替换字符串

2024-10-03 09:18:56 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我正在创建一个madLib,我想替换包含单词'plural noun'的字符串中的每个单词。基本上,用户会得到一个提示,提示输入复数名词,这些输入会转到字典(pluralnoDict

我一直在使用random.choice,并且一直在工作,但是,重复显然是个问题。我尝试了random.sample,但是,代码没有从给定的示例中选择一个单词,而是用整个示例替换这些单词

是否有一种方法可以使用字典列表中的random.sample替换每个字符串?例如:

原文'plural noun''plural noun''plural noun'。 应为:'birds'具有'wings''feet'

下面是我用来替换复数名词字符串的for循环

for key in pluralnoDict:
        target_word = "({0})".format(key)
        while target_word in madString:
            madString = madString.replace(target_word, random.choice(pluralnoDict[key]), 1)

Tags: samplekey字符串target字典random单词word
2条回答

你查过random图书馆了吗?您可以使用它获得随机索引,因此,据我所知,可能的解决方案如下所示:

import re
import random

list_of_words = ["dogs", "cats", "mice"]

mad_lib = "the quick brown plural noun jumped over the lazy plural noun"

while "plural noun" in mad_lib:
    random_index = random.randint(0, len(list_of_words))
    mad_lib = re.sub("plural noun", list_of_words[random_index], mad_lib, 1)
    del list_of_words[random_index]

print(mad_lib)

如果您想使用所有的名词,但顺序是随机的,您可以使用random.shuffle并执行如下操作:

from random import shuffle

target_word = "plural noun"
mad_str = "The 'plural noun' have 'plural noun' and 'plural noun'"
plural_nouns = ["birds", "feet", "wings"]
shuffle(plural_nouns)
for noun in plural_nouns:
    mad_str = mad_str.replace(target_word, noun, 1)
print(mad_str)

相关问题 更多 >