![](/img/trans.png)
[英]'TypeError: list indices must be integers, not str' Python 3
[英]Python chatbot - TypeError: list indices must be integers, not str
我使用Python创建了一个简单的聊天机器人,但是当我尝试使用它时,它给了我一个错误: TypeError: list indices must be integers, not str
。
稍后,我将介绍该错误,但首先,我将说明该机器人应该做什么。 机器人具有一个由字典表示的数据库,其中存储了用户和机器人的所有响应。
(对不起,如果解释不好,但是如果您继续阅读,可能会明白。)
因此,这是机器人应该做什么的一个例子。
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!
这是我正在使用的代码(我排除了不需要的部分)
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> "))
现在,我遇到了问题。
当我尝试与漫游器通信时,出现错误TypeError: list indices must be integers, not str
。 它指向代码self.database[text] = []
。 这是一个例子:
BOT> Hi!
YOU> Hello!
(error)
我不知道发生了什么,所以我不知道应该怎么做才能修复它。 我以为代码可以正常工作,但是不行。有人可以给我一点帮助吗?
self.database
是一个列表。 通过指定列表项在列表中的位置来访问列表项,例如,第一项为self.database[0]
,第五项为self.database[4]
。
您试图将text
用作列表位置,这没有任何意义。
如果要基于文本键而不是整数位置存储项目,请使用字典而不是列表。
您提到数据库是一个字典,但是您正在创建一个列表
self.database = []
用大括号创建dict
self.database = {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.