Python聊天机器人报UnboundLocalError: responses赋值前引用如何解决
问题报错原因
运行chat()函数触发的局部变量引用错误,核心原因是变量responses的赋值逻辑存在漏洞:
responses仅在遍历data["intents"]、且匹配到和预测结果一致的tag时才会被赋值- 遍历结束后代码会直接执行
random.choice(responses),没有做任何存在性校验 - 只要出现任意一种异常场景:预测返回的tag不在intents列表里、intents列表为空,整个遍历过程都不会给
responses赋值,此时Python识别到你要引用一个还没完成赋值的局部变量,就会抛出对应错误。
触发的报错信息:
UnboundLocalError: local variable 'responses' referenced before assignment
修复方案
最稳妥的修复方式是提前初始化responses变量,匹配到对应tag时再覆盖赋值,同时增加匹配结果校验,匹配失败时直接走兜底回复逻辑,修正后的完整代码如下:
def chat(): print("Start talking with the bot (type quit to stop)!") while True: inp = input("You: ") if inp.lower() == "quit": break results = model.predict([bag_of_words(inp, words)])[0] results_index = numpy.argmax(results) tag = labels[results_index] if results[results_index] > 0.7: # 提前初始化responses,从根源避免未赋值引用问题 responses = [] for tg in data["intents"]: if tg['tag'] == tag: responses = tg['responses'] # 匹配到目标tag后直接跳出循环,减少不必要的遍历 break # 校验是否拿到有效回复列表 if responses: print(random.choice(responses)) else: print("I couldn't get what u meant.") else: print("I couldn't get what u meant.") chat()
修复点说明
- 进入高置信度分支后第一时间初始化
responses为空列表,保证后续引用时变量一定存在 - 匹配到对应tag后直接break终止循环,不需要遍历完所有intents条目,运行效率更高
- 增加responses非空校验,就算tag匹配失败也不会报错,直接复用低置信度场景的兜底提示,逻辑更统一。
内容的提问来源于stack exchange,提问作者dilanur kök
相关产品推荐
相关产品推荐

