【发布时间】: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