我正在用Python构建一个聊bot。我在运行代码时遇到了问题

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

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注