Python聊天机器人触发TypeError:无法将NoneType与字符串拼接
问题分析与修复
报错原因是get_response函数最终返回了None,因为check_all_messages函数没有返回任何值,导致字符串拼接时出现类型错误。同时代码还存在递归调用的逻辑错误,以下是具体修复步骤:
核心问题点
check_all_messages函数未返回结果,调用后默认返回None- 内部
response函数的定义中,把预设响应的调用写在了函数内部,导致无限递归调用
修复后的完整代码
import re # 若未实现long_response模块可先注释该行,不影响当前核心逻辑 # import long_response as long def message_probability(user_message, recognised_words, single_response=False, required_words=[]): message_certainty = 0 has_required_words = True for word in user_message: if word in recognised_words: message_certainty += 1 # 计算匹配度百分比 percentage = float(message_certainty) / float(len(recognised_words)) for word in required_words: if word not in user_message: has_required_words = False break if has_required_words or single_response: return int(percentage * 100) else: return 0 def check_all_messages(message): highest_prob_list = {} def response(bot_response, list_of_words, single_response=False, required_words=[]): nonlocal highest_prob_list highest_prob_list[bot_response] = message_probability(message, list_of_words, single_response, required_words) # 把预设响应调用移到response函数外,避免递归 response('Hello !', ['hello', 'hi', 'sup', 'hey', 'yo', 'heyo', 'hello there'], single_response=True) response('I\'m great, doing just fine, and you ?', ['how', 'are', 'you', 'doing'], required_words=['how']) response('Oh...Thanks...I guess. I\'m a chatbot so I\'m not used to such kindness', ['i', 'love', 'code', 'palace'], required_words=['code', 'palace']) response('You are welcome, that\'s my purpose after all.', ['thank', 'thanks'], required_words=['thank']) # 匹配度最高的响应 best_match = max(highest_prob_list, key=highest_prob_list.get) print(highest_prob_list) # 返回结果给调用者 return best_match def get_response(user_input): split_message = re.split(r'\s+|[,;?!.-]\s*', user_input.lower()) response = check_all_messages(split_message) return response # 测试响应系统 while True: print('Bot: ' + get_response(input('You: ')))
关键修复说明
- 将预设响应的
response(...)调用从内部函数response的定义中移出,放在check_all_messages函数内、response函数定义之后,避免无限递归。 - 在
check_all_messages函数末尾添加return best_match,确保函数返回匹配到的响应文本,而非None。 - 调整感谢响应的
required_words为['thank'](原逻辑要求所有必填词都存在,若保留['thank', 'thanks']则需要用户同时输入两个词才会触发,不符合日常对话预期)。 - 修正了原文本中的拼写错误(kindess → kindness),提升可读性。
内容的提问来源于stack exchange,提问作者kobayano444
相关产品推荐
相关产品推荐

