我的任务是创建一个随机的compliment生成器,它使用两个for循环随机选择和替换句子中的名词和形容词。我应该使用random.choice功能来选择名词/形容词,然后用替换物打印出这个句子。我在下面做了大部分工作,但由于某种原因,程序只是替换名词而不是形容词。相反,它会在占位符后打印出想要的形容词。如何使用两个for循环来随机替换一个句子中的多个单词
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'的好时机# – shuttle87