使用Python的ChatterBot库开发数学聊天机器人时遭遇AttributeError错误的修复咨询
使用Python的ChatterBot库开发数学聊天机器人时遭遇AttributeError错误的修复咨询
嘿,我来帮你排查这个问题~
你遇到的AttributeError: 'NoneType' object has no attribute 'text'错误,根源在于代码里的result变量在某些情况下没有被赋值,变成了None,后面调用result.text自然就报错了。
咱们来看那段出问题的逻辑:
# If multiple adapters agree on the same statement, # then that statement is more likely to be the correct response if len(results) >= 3: # ... 中间的共识判断代码 ... if most_common.count > 1: result = most_common.statement # Always the console says this response = Statement( # error is here !! text=result.text, # ... 其他参数 ... )
这段代码是为多个逻辑适配器共存的场景设计的:只有当返回的结果数量≥3,且有超过1个适配器达成共识时,才会给result赋值。但你的机器人只配置了MathematicalEvaluation这一个适配器,results的长度永远是1,完全不满足len(results)>=3的条件,所以result一直是未定义的状态,到后面调用result.text时就变成了None。
这里有两种简单的修复方式:
方案一:给result设置默认值
在那段多适配器判断逻辑之前,先把result初始化为results里的第一个结果,这样不管是否满足多适配器条件,result都有值:
# 先设置默认结果,适配单适配器场景 result = results[0] # 原有的多适配器共识判断逻辑 if len(results) >= 3: result_options = {} for result_option in results: result_string = result_option.text + ':' + (result_option.in_response_to or '') if result_string in result_options: result_options[result_string].count += 1 if result_options[result_string].statement.confidence < result_option.confidence: result_options[result_string].statement = result_option else: result_options[result_string] = ResultOption(result_option) most_common = list(result_options.values())[0] for result_option in result_options.values(): if result_option.count > most_common.count: most_common = result_option if most_common.count > 1: result = most_common.statement
方案二:简化逻辑(更适合你的场景)
既然你只用到了一个数学计算适配器,完全可以删掉那段多适配器的共识判断逻辑,直接取结果就行:
# 单适配器场景下,直接取第一个结果 result = results[0] # 直接构建response response = Statement( text=result.text, in_response_to=input_statement.text, conversation=input_statement.conversation, persona='bot:' + self.name ) response.confidence = result.confidence return response
修改完成后,再运行你的聊天机器人代码,输入类似3*5或者10-4的数学问题,应该就能正常返回计算结果,不会再出现这个错误啦~
备注:内容来源于stack exchange,提问作者saito.py
相关产品推荐
相关产品推荐

