我正在用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

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

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