import randomuserKeywords = {"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构建一个聊bot。我在运行代码时遇到了问题。我的目标是创建一个函数,该函数在一个数组中搜索问候关键词。如果数组中存在该关键词,机器人会以类似的回应做出反应。例如,如果用户输入”hello”,机器人必须识别到”hello”是问候关键词之一,并通过从”machineResponses”中随机选择一个回应,打印出类似于”hello”的字符串作为回应。我收到了以下错误:
print(machineAnswer(message))File "C:\Users\gilbe\eclipse-workspace\python3.6\BeginnerFiles\ChatBot", line 9, in machineAnswerreturn random.choice(machineResponses)File "C:\Users\gilbe\AppData\Local\Programs\Python\Python36-32\lib\random.py", line 259, in choicereturn seq[i]TypeError: 'set' object does not support indexing
回答:
random.choice 从对象中随机选择一个索引,但您使用的是不支持索引的集合。您可以将集合转换为列表并使用它
集合只是唯一元素的无序集合。因此,一个元素要么在集合中,要么不在。这意味着集合中的元素没有索引。
import randomuserKeywords = {"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