假设我正在创建一个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)
你查过
random
图书馆了吗?您可以使用它获得随机索引,因此,据我所知,可能的解决方案如下所示:如果您想使用所有的名词,但顺序是随机的,您可以使用
random.shuffle
并执行如下操作:相关问题 更多 >
编程相关推荐