2016-10-11 51 views
0

我的任务是创建一个随机的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时,程序返回它超出范围。

+0

这是使用'enumerate'的好时机# – shuttle87

回答

0

您递增之前你做了一个形容词检查,这意味着,你做,你基本上是越来越替代:

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

这就解释了为什么字一个“*形容词”正在被修改。在检查形容词后,请移动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) 
+0

哇!列举是我根本没有教过的东西。不要手动将indexCount设置为0,非常方便。我将尝试此解决方案并回复给您。 – Dev

+0

我尝试了枚举方法,但是我一直听到说句子[idx] = wordChoice的错误。它说wordChoice没有定义。 – Dev

+0

@Dev啊是的,这是一个错误,现在应该修复 – shuttle87

0

让我们简单:

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. 
+0

哎呀 - 我没有首先获得for循环的要求。 – bubthegreat

+0

感谢评论!如果我没有强制要求使用循环,那么这可能是我想要的。这很简单,但是,它不符合要求。 – Dev

相关问题