Python调用random.choice()从数组取单个随机值报错排查
报错根因
两个核心问题导致报错和逻辑不符合预期:
bot.get_response(message)的返回值是ChatterBot匹配后输出的单个字符串,不是你定义的responses数组。对字符串调用random.choice()时,方法会把字符串拆成独立字符随机选取,既拿不到完整回复,也会触发类型逻辑错误。- 你的代码根本没有加载解析写好的intents JSON配置,只是把文件按纯文本逐行读取喂给训练器,JSON里的括号、键名、tag字段都会被当成普通对话内容参与训练,和你预设的意图分组、响应列表完全没有关联。
修复方法
选其中一种方案调整即可:
方案1:用ChatterBot自带的随机响应配置(改动最小)
初始化ChatBot实例时指定随机选择响应的规则,不需要自己额外调用random.choice(),同时修正JSON文件的读取逻辑:
from chatterbot import ChatBot from chatterbot.trainers import ListTrainer import os import json import random # 初始化时配置随机选回复的逻辑 bot = ChatBot( "Test", response_selection_method=lambda resp_list: random.choice(resp_list) ) trainer = ListTrainer(bot) data_path = "C:/Users/Patty/Desktop/chatbotUI/ints/" for file in os.listdir(data_path): # 只处理json格式的意图文件,正确解析结构 if file.endswith('.json'): with open(data_path + file, 'r', encoding='utf-8') as f: intents_config = json.load(f) # 按意图分组把匹配问法和对应回复喂给训练器 for intent in intents_config['intents']: training_corpus = intent['patterns'] + intent['responses'] trainer.train(training_corpus) while True: message = input("You: ") if message.strip() == "Bye": print("ChatBot: Farewell") break # get_response会直接返回随机选中的单条回复,无需再做随机选取 response = bot.get_response(message) print("ChatBot: ", response)
方案2:自行匹配意图后从响应列表随机抽取
如果你要自己控制匹配逻辑,可以先把所有意图的响应列表提前加载到字典里,匹配到对应意图后再对响应列表调用random.choice():
# 提前加载所有意图的响应映射 intent_map = {} for file in os.listdir(data_path): if file.endswith('.json'): with open(data_path + file, 'r', encoding='utf-8') as f: intents_config = json.load(f) for intent in intents_config['intents']: for pattern in intent['patterns']: intent_map[pattern] = intent['responses'] # 对话循环内完成匹配后,再对列表类型的响应集合做随机选取 # 示例:匹配到用户输入对应greeting的响应列表res_list后 # answer = random.choice(res_list)
注意:
random.choice()仅支持传入列表、元组这类可迭代的序列类型,不要直接传入字符串、整数这类非序列类型参数。
内容的提问来源于stack exchange,提问作者54V4G3208
相关产品推荐
相关产品推荐

