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

I am building a chatbot in python. I am having trouble running the code

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 中构建一个聊天机器人。我遇到了代码问题 运行。我的目标是创建一个函数,用于在数组中搜索问候语 keyword.If 关键字存在于数组中,机器人会以类似的响应进行响应。例如,如果用户输入 "hello",机器人必须识别出 hello 是问候关键字之一,并通过从 "machineResponses" 中随机选择一个响应来打印出与 "hello" 相似的字符串作为响应].我收到以下错误:

print(machineAnswer(message))
File "C:\Users\gilbe\eclipse-workspace\python3.6\BeginnerFiles\ChatBot", line 9, in machineAnswer
return random.choice(machineResponses)

File "C:\Users\gilbe\AppData\Local\Programs\Python\Python36-32\lib\random.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 = 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")

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

A set is just an unordered collection of unique elements. So, an element is either in a set or it isn't. This means that no element in a set has an index.

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

我会试试这个:

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")

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