【问题标题】:How to use two for loops to randomly replace multiple words in a sentence如何使用两个for循环随机替换一个句子中的多个单词
【发布时间】:2017-02-19 12:33:08
【问题描述】:

我的任务是创建一个随机赞美生成器,它使用两个 for 循环来随机选择和替换句子中的名词和形容词。我应该使用 random.choice 函数来选择名词/形容词,然后打印出带有替换的句子。我已经在下面完成了大部分工作,但由于某种原因,该程序只替换了名词而不是形容词。相反,它会在占位符之后打印出预期的形容词。

import random

sentence = "Hi, your *noun is looking *adj today."
sentence = sentence.split()

nouns = ["son", "daughter", "dog", "house"]
adjectives = ["beautiful", "handsome", "pretty", "warm", "fantastic"]

indexCount = 0
for word in sentence:
    if word == "*noun":
        wordChoice = random.choice(nouns)
        sentence[indexCount] = wordChoice
    indexCount += 1

    if word == "*adj":
        wordChoice = random.choice(adjectives)
        sentence[indexCount] = wordChoice

st = ""
for word in sentence:
    st += word + " "
print(st)

我在 IDLE 中不断得到的输出类似于:

 Hi, your son is looking *adj warm 

今天根本没有打印出来。当我尝试添加第二个 indexCount += 1 时,程序返回它超出范围。

【问题讨论】:

  • 这是使用enumerate的好时机

标签: python-3.x for-loop random


【解决方案1】:

您在检查形容词之前在增加,这意味着您在哪里进行替换,您基本上得到了:

if word == "*adj":
    wordChoice = random.choice(adjectives)
    sentence[(indexCount+1)] = wordChoice

这解释了为什么单词 one after "*adj" 被修改了。而是在检查形容词之后移动indexCount 的增量。

更好的是使用enumerate 来获取索引:

for idx, word in enumerate(sentence):
    if word == "*noun":
        wordChoice = random.choice(nouns)
        sentence[idx] = wordChoice

    if word == "*adj":
        wordChoice = random.choice(adjectives)
        sentence[idx] = wordChoice

此外,在构建结果时,您不妨使用join:

st = " ".join(sentence)

【讨论】:

  • 哇!枚举是我根本没有教过的东西。不用手动将 indexCount 设置为 0 非常方便。我会尝试这个解决方案并回复您。
  • 我尝试了 enumerate 方法,但我不断收到一个错误,即语句 [idx] = wordChoice.它说没有定义 wordChoice。
  • @Dev 啊是的,这是一个错误,现在应该修复
  • 感谢您的帮助!它现在完美运行。现在我必须完全理解它,并且能够在我的实际明天使用它。感谢您提供有关枚举和加入的有用提示,它们将为我节省大量时间。
  • @Dev 很高兴为您提供帮助!如果此问题对您有帮助,您可以通过选中旁边的复选标记将其标记为已接受的答案。
【解决方案2】:

让我们变得更简单:

import random
nouns = ["son", "daughter", "dog", "house"]
adjectives = ["beautiful", "handsome", "pretty", "warm", "fantastic"]

现在一个简单的打印语句,虽然很长,但超级好用:

print "Hi, your", random.choice(nouns), "is looking", random.choice(adjectives), "today."
Hi, your dog is looking beautiful today.

【讨论】:

  • 哎呀 - 我没有首先得到 for 循环的要求。
  • 感谢您的评论!如果我没有被强制使用 for 循环,这可能就是我会使用的。确实很简单,但是不符合要求。
猜你喜欢
  • 1970-01-01
  • 2019-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-06
  • 1970-01-01
相关资源
最近更新 更多