我正在python中构建一个聊天机器人。我无法运行代码

时间:2018-05-27 07:30:24

标签: python python-3.x artificial-intelligence chatbot

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中构建一个聊天机器人。我无法运行代码。我的目标是创建一个函数,在数组中搜索greeting关键字。如果关键字存在于数组中,则bot会响应类似的响应。例如,如果用户输入“hello”,则bot必须通过从“machineResponses”中随机选择响应来识别hello是问候关键字之一并打印出类似的字符串“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

3 个答案:

答案 0 :(得分:0)

您可以减少迭代并检查。 你的陈述的问题是random.choice不支持set object。

SqlCommand cmd = new SqlCommand("delete from Spempdet where Id= ' " + ID+" ' " , con);

答案 1 :(得分:0)

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

答案 2 :(得分:0)

我想试试这个:

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

当我尝试的时候它奏效了。