[英]Python chatbot - TypeError: list indices must be integers, not str
I've created a simple chatbot using Python, but when I try to use it, it gives me an error: TypeError: list indices must be integers, not str
. 我使用Python创建了一个简单的聊天机器人,但是当我尝试使用它时,它给了我一个错误:
TypeError: list indices must be integers, not str
。
I'll get into the error later, but first I'll explain what the bot should do. 稍后,我将介绍该错误,但首先,我将说明该机器人应该做什么。 The bot has a database, represented by a dictionary, in which all of the user's and bot's responses are stored.
机器人具有一个由字典表示的数据库,其中存储了用户和机器人的所有响应。
(Sorry if the explanation was bad, but maybe if you keep reading you might understand.) (对不起,如果解释不好,但是如果您继续阅读,可能会明白。)
So, here is an example of what the bot should do. 因此,这是机器人应该做什么的一个例子。
BOT> Hi!
YOU> Hello!
BOT> Hello!
YOU> How do you do?
BOT> How do you do?
YOU> I'm fine, thanks.
BOT> I'm fine, thanks.
YOU> Hello!
BOT> How do you do?
YOU> I'm fine thanks.
BOT> Hello!
Here's the code I'm using (I excluded the parts that aren't needed) 这是我正在使用的代码(我排除了不需要的部分)
import pickle
import random
class Bot:
def __init__(self, current, database, saveFile):
self.current = "Hi!"
self.database = []
def say(self, text):
print("BOT> " + text)
self.current = text
def evaluate(self, text):
if text in self.database:
self.say(random.choice(self.database[text]))
else:
self.database[text] = []
self.say(text)
bot = Bot("", {})
bot.say("Hi!")
while 1:
bot.evaluate(input("YOU> "))
And now, onto the problem I'm having. 现在,我遇到了问题。
When I try to talk to the bot, I get the error TypeError: list indices must be integers, not str
. 当我尝试与漫游器通信时,出现错误
TypeError: list indices must be integers, not str
。 It was pointing to the line of code self.database[text] = []
. 它指向代码
self.database[text] = []
。 Here's an example: 这是一个例子:
BOT> Hi!
YOU> Hello!
(error)
I don't know what's going on, so I don't know what I should do to try and fix it. 我不知道发生了什么,所以我不知道应该怎么做才能修复它。 I thought the code would work right, but it doesn't... Could anybody give me a little help?
我以为代码可以正常工作,但是不行。有人可以给我一点帮助吗?
self.database
is a list. self.database
是一个列表。 List items are accessed by specifying their position within the list, for example self.database[0]
for the first item and self.database[4]
for the fifth item. 通过指定列表项在列表中的位置来访问列表项,例如,第一项为
self.database[0]
,第五项为self.database[4]
。
You're trying to use text
as a list position, which makes no sense. 您试图将
text
用作列表位置,这没有任何意义。
If you want to store items based on a text key instead of an integer position, use a dictionary instead of a list. 如果要基于文本键而不是整数位置存储项目,请使用字典而不是列表。
You mention the database is a dictionary, yet you're creating a list 您提到数据库是一个字典,但是您正在创建一个列表
self.database = []
A dict
is created by curly braces 用大括号创建
dict
self.database = {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.