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

Python代码在Colab运行报list indices must be integers错误如何解决

代码报错修复方案

错误根因

报错list indices must be integers or slices, not str的核心原因是:当前intents变量为列表类型,但代码用了字符串'intents'作为索引取值,列表仅支持整数或切片作为索引。

快速验证方法

运行以下代码确认intents的实际结构:

print(type(intents))
print(intents[:2])
  • 如果输出类型为list,且打印内容能直接看到patterns、tag这类键,属于场景1
  • 如果输出类型为dict,且外层唯一键为intents,属于场景2

对应修改方案

场景1:intents本身就是存储所有意图的列表

删除第一层循环的冗余取值即可,修改后代码如下:

for intent in intents: 
    for pattern in intent['patterns']:
        w = nltk.word_tokenize(pattern)
        words.extend(w)
        documents.append((w, intent['tag']))
        if intent['tag'] not in classes:
            classes.append(intent['tag'])

场景2:intents应为外层嵌套字典

检查你读取意图文件的代码,确认你没有提前取内层intents列表,示例正确的json读取逻辑:

import json
with open("你的意图配置文件路径.json", "r", encoding="utf-8") as f:
    # 直接将完整json字典赋值给intents,不要额外加['intents']
    intents = json.load(f)

该场景下原循环代码无需修改。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 12:54:03