You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python聊天机器人代码报错:'set'对象不支持索引问题求助

问题排查与解决:集合不支持索引导致的random.choice()错误

首先,咱们直接揪出报错的核心原因:random.choice()这个函数要求传入支持下标索引的序列类型(比如列表、元组),但你把机器回复的集合machineResponses定义成了set(用大括号包裹的集合)。集合是无序的,而且不允许通过seq[i]这种下标方式访问元素,所以调用random.choice()的时候就触发了TypeError。

接下来给你分两个层面修复,先解决核心报错,再优化代码体验:

1. 核心错误修复(直接解决报错)

只需要把machineResponses从集合改成列表就行,把大括号{}换成方括号[],修改后的完整代码如下:

import random

userKeywords = {"hi","hello","wassup","what'sup","greetings","sup","henlo","que onda","hola","hey","waddup"}
# 把集合改成列表,支持索引访问
machineResponses = ["hello", "Hello there, I am a bot", "greetings from inside this computer"]

def machineAnswer(message):
    for key in userKeywords:
        if key == message:
            return random.choice(machineResponses)
    # 添加默认返回值,避免无匹配时打印None
    return "Sorry, I don't get what you're saying."

def respondTo(message):
    print(machineAnswer(message))

respondTo("hello")

运行这段代码,索引错误就会消失,输入"hello"会随机返回一条问候回复。

2. 代码体验优化(可选但实用)

原代码是严格大小写匹配的,比如用户输入"Hello"或者"HELLO"就匹配不到。咱们可以优化匹配逻辑,把用户输入转成小写后再匹配,同时用集合的in操作符替代循环,效率更高:

import random

userKeywords = {"hi","hello","wassup","what'sup","greetings","sup","henlo","que onda","hola","hey","waddup"}
machineResponses = ["hello", "Hello there, I am a bot", "greetings from inside this computer"]

def machineAnswer(message):
    # 转小写实现不区分大小写的匹配,用in操作符更简洁高效
    if message.lower() in userKeywords:
        return random.choice(machineResponses)
    return "Sorry, I don't understand that."

def respondTo(message):
    print(machineAnswer(message))

# 现在输入"Hello"、"HELLO"都能正常触发问候回复了
respondTo("Hello")

内容的提问来源于stack exchange,提问作者g24

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:04:25