如果userinput包含多个单词,python中的Chatbot会生成随机答案

如果userinput包含多个单词,python中的Chatbot会生成随机答案,python,Python,我的问题是,如果userinput包含多个单词,我的程序会随机生成一个随机答案,即使我不想这样做。我的意思是我理解为什么程序会生成一个随机的答案,但是我如何才能克服这个问题呢 这是我的密码: import random print("Welcome to Chatbot! Have fun.") print("") randomanswer = ['Thats not good', 'me too', 'how about you?'] reaction

我的问题是,如果userinput包含多个单词,我的程序会随机生成一个随机答案,即使我不想这样做。我的意思是我理解为什么程序会生成一个随机的答案,但是我如何才能克服这个问题呢

这是我的密码:

import random

print("Welcome to Chatbot! Have fun.")
print("")
randomanswer = ['Thats not good', 'me too', 'how about you?']
reactionanswer = {'hello': 'hello, whats up?',
                  'sad': 'speak to me',
                  'entertainment': 'how can i entertain you?'}
userinput = ''
while True:
    userinput = input("Question/Answer: ")
    userinput = userinput.lower()
    if userinput == 'bye':
        print("See you soon!")
        break
    else:
        usersplit = userinput.split()
        for i in usersplit:
            if i in reactionanswer:
                print(reactionanswer[i])
            else:
                print(random.choice(randomanswer))


对我来说效果很好,我完全运行了您的代码并得到以下结果:

Question/Answer: hello guy
hello, whats up?
Thats not good

Question/Answer: nothing in the list
me too
me too
me too
Thats not good

也可以写几个单词。这取决于什么是有效的意思——你写道,对于每个不在已知列表中的单词,它将生成随机答案。对于任何已知的单词,它都会按照你的意愿来回答。在第一种情况下,第一个单词生成了第一个已知答案,第二个单词生成了随机答案。明确哪些地方没有达到预期效果。

问题是,即使找到了答案,for循环仍会继续运行。如果在答案中找到单词,则添加“break”语句。像这样:

    else:
        usersplit = userinput.split()
        for i in usersplit:
            if i in reactionanswer:
                print(reactionanswer[i])
                break < --- add this
            else:
                print(random.choice(randomanswer))
其他:
usersplit=userinput.split()
对于usersplit中的i:
如果我在回答:
打印(反应回答[i])
打断<---加上这个
其他:
打印(随机选择(随机回答))

请在问题中包括预期输出和您得到的输出。@python\u初学者您正在迭代
userinput.split()
,其中包含来自输入的拆分单词列表。2个单词=包含2个元素的列表。。。