python - 使用 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)
解决方案
你看过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)
推荐阅读
- python - 使用多索引上的条件选择数据帧的子集
- java - 在按钮单击时将数据传递给新活动
- javascript - 一秒钟后,我的 php 生成的表单从 HTML 页面中消失了
- coldfusion - 我可以在 cfscript 中使用 cfdocument 吗?
- python - 如何在 Python 中后退一步?
- laravel - 将Vue数据传递给php
- php - 代码背后的逻辑?
- node.js - mongodb 文档中的附加 id 字段
- c# - 时间:2019-05-10 标签:c#get info from query that exist or was created
- objective-c - 符合 Objective-C 中类别的协议