首页 > 解决方案 > 使用 random.sample 将字符串替换为字典中的值

问题描述

假设我正在创建一个 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)

标签: pythondictionaryrandom

解决方案


你看过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)

推荐阅读