我试图制作一个聊天机器人,随机问你问题,但我不断得到"TypeError: can only concatenate list (not " ") to list"



https://i.stack.imgur.com/v1zRC.png

我试着制作一个聊天机器人,随机问你问题,但我一直得到";TypeError:只能将列表(而不是"str")连接到列表";我不知道该怎么办。

import random
username = ""
username = input("What would you like me to call you?")

questions = [
'What is your favorite color?',
'What is your favorite animal?', 
'What are your thoughts on call of duty?',
'Do you like minecraft?' ,
'What do you do to get rid of stress?',
'What three words best describe you?',
'What’s your favorite number? Why?',
'What do you think of tattoos? Do you have any?',
'Do you have any pets? What are their names?'
]


def generate_response(user_input):
responses = [
"How interesting "+ username + "!",
"You don't say "+ username +"!",
"Very cool "+ username +"!",
"ok "+ username
]
return random.choice(responses)

def init_chat():
quit_character = 'q'
user_input = input("Hello, how are you " + username + "?n")
print(random_question + username)
while user_input != quit_character:
user_input = input(generate_response(user_input) + "n")
random_question = random.choices(questions)
generate_response()
if __name__ == "__main__":
init_chat()

您在代码的第41行收到一个TypeError,因为您正试图将列表(random_question)与字符串(username)连接起来。

在第22行,你写

random_question = random.choices(questions) 

random.choices()返回一个列表。使用

random_question = random.choice(questions) 

如果你只想从问题中得到一个元素。

相关内容

最新更新