我正在用python构建一个聊天机器人.我在运行代码时遇到问题


import random
userKeywords = {"hi","hello","wassup","what'sup","greetings","sup","henlo","que onda","hola","hey","waddup"}
machineResponses = {"hello", "Hello there, I am a bot", "greetings from inside this computer"}
def machineAnswer(message):
for key in userKeywords:
if key == message:
return random.choice(machineResponses)
def respondTo(message):
print(machineAnswer(message))
respondTo("hello")

我正在用python构建一个聊天机器人。我在运行代码时遇到问题。我的目标是创建一个函数,在数组中搜索问候关键字。如果数组中存在关键字,则机器人将使用类似的响应进行响应。例如,如果用户输入"hello",机器人必须识别 hello 是问候关键字之一,并通过从"machineResponses"中随机选择响应来打印出与"hello"类似的字符串作为响应。我收到以下错误:

print(machineAnswer(message))
File "C:Usersgilbeeclipse-workspacepython3.6BeginnerFilesChatBot", line 9, in machineAnswer
return random.choice(machineResponses)
File "C:UsersgilbeAppDataLocalProgramsPythonPython36-32librandom.py", line 259, in choice
return seq[i]
TypeError: 'set' object does not support indexing

Random.choice 从对象中获取随机索引,但您使用的是不支持索引的集合,您可以将集合转换为列表并使用它

集合

只是唯一元素的无序集合。所以,一个 元素要么在集合中,要么不在集合中。这意味着没有元素 集合有一个索引。

import random
userKeywords = {"hi","hello","wassup","what'sup","greetings","sup","henlo","que onda","hola","hey","waddup"}
machineResponses = ["hello", "Hello there, I am a bot", "greetings from inside this computer"]
def machineAnswer(message):
for key in userKeywords:
if key == message:
return random.choice(machineResponses)
def respondTo(message):
print(machineAnswer(message))
respondTo("hello")

输出:

Hello there, I am a bot

您可以减少迭代和检查。 您的语句的问题是随机的。choice 不支持 set 对象。

import random
userKeywords = {"hi","hello","wassup","what'sup","greetings","sup","henlo","que onda","hola","hey","waddup"}
machineResponses = list({"hello", "Hello there, I am a bot", "greetings from inside this computer"})
def machineAnswer(message):
if message in userKeywords:
return random.choice(machineResponses)
def respondTo(message):
print(machineAnswer(message))
respondTo("hello")

我会试试这个:

import random
userKeywords = ["hi","hello","wassup","what'sup","greetings","sup","henlo","que onda","hola","hey","waddup"]
machineResponses = ["hello", "Hello there, I am a bot", "greetings from inside this computer"]
def machineAnswer(message):
if message in userKeywords:
return machineResponses[random.randint(0, 2)]
def respondTo(message):
print(machineAnswer(message))
respondTo("hello")

当我尝试它时,它起作用了。

最新更新