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
.
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
. It was pointing to the line of code 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. 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.
You're trying to use text
as a list position, which makes no sense.
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
self.database = {}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.