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

问题描述 投票:0回答:2

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

我一直在使用 random.choice但是,很明显是重复的问题。我试过 random.sample然而,代码不是从一个给定的样本中选择一个词,而是用整个样本替换这些词。

有什么方法可以让我用 random.sample 从字典列表中?例如:?

原版 The '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)
python dictionary random
2个回答
0
投票

如果你想使用所有的名词,但顺序是随机的,你可以使用 "复数名词"。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)

1
投票

你有没有调查过 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)
© www.soinside.com 2019 - 2024. All rights reserved.