聊天机器人开发遇TypeError:'_io.TextIOWrapper'对象不可下标访问
修复聊天机器人的TypeError及相关问题
核心错误原因
报错TypeError: '_io.TextIOWrapper' object is not subscriptable是因为你直接把文件对象当成字典来用了——open()函数返回的是文件句柄,不是JSON解析后的字典,必须用json.load()加载文件内容才能得到字典结构。
其他待修复问题
除核心错误外,代码还有两处语法/逻辑问题:
find_best_match函数错误地提前返回类型注解,导致后续匹配逻辑无法执行;- 生成问题列表的代码语法错误,无法正确提取知识库中的问题文本。
完整修复代码
依赖函数(修复后)
import json from difflib import get_close_matches def save_knowledge_base(file_path: str, data: dict): with open(file_path, 'w') as file: json.dump(data, file, indent=2) def find_best_match(user_question: str, questions: list[str]) -> str | None: matches: list = get_close_matches(user_question, questions, n=1, cutoff=0.6) return matches[0] if matches else None def get_answer_for_question(question: str, knowledge_base: dict): for q in knowledge_base["questions"]: if q["question"] == question: return q["answer"]
主函数(修复后)
def AXIS(): # 修复:用json.load加载文件为字典,with语句自动管理文件资源 with open('knowledge_base.json', 'r', errors='ignore') as f: knowledge_base: dict = json.load(f) while True: user_input: str = input('You: ') if user_input.lower() in ("q", "quit", "shut down", "shutdown", "cancel", "power off", "poweroff", "power down", "powerdown", "off", "turn off", "turnoff"): print("AXIS: powering down") break # 修复:正确提取知识库中的问题列表 questions = [q["question"] for q in knowledge_base["questions"]] best_match: str | None = find_best_match(user_input, questions) if best_match: answer: str = get_answer_for_question(best_match, knowledge_base) print(f'AXIS: {answer}') else: print('AXIS: I don\'t know the answer. Please teach me?') new_answer: str = input('Type the answer or "skip" to skip: ') if new_answer.lower() != 'skip': knowledge_base["questions"].append({"question": user_input, "answer": new_answer}) save_knowledge_base('knowledge_base.json', knowledge_base) print('AXIS: I have learned a new response!') if __name__ == '__main__': AXIS()
关键修复点说明
- 文件加载修复:使用
with open(...) as f配合json.load(f)将JSON文件内容解析为Python字典,避免文件对象误用; - 函数返回值修复:把
find_best_match的返回值类型注解移到函数定义末尾(-> str | None),删除错误的提前return语句; - 问题列表生成修复:用列表推导式
[q["question"] for q in knowledge_base["questions"]]正确提取所有问题文本,传入匹配函数。
内容的提问来源于stack exchange,提问作者thewatcher
相关产品推荐
相关产品推荐

