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

如何修复JSON文件中的TypeError: string indices must be integers错误

解决DataFrame转Hugging Face数据集时的TypeError问题

错误原因

  1. JSON序列化重复操作:代码中多次对数据进行JSON序列化/反序列化,最后用json.dump()写入已序列化的字符串,导致文件内容是被转义的JSON字符串而非预期的JSON对象结构。
  2. 数据结构不匹配:读取后intents是一个列表(每个元素为含单条记录的{'intents': [...]}字典),但后续代码试图用intents['intents'](字符串索引)访问列表,触发TypeError: string indices must be integers。
  3. 意图结构构造错误:原代码将每条记录单独包裹为{'intents': [record]}并放入列表,不符合后续处理所需的「单字典+intents键对应所有记录列表」的结构。

修复方案

调整JSON构造与写入逻辑,直接生成符合预期的数据结构,避免重复序列化操作:

修改后的完整代码片段

import pandas as pd
import json
import nltk

# 假设preprocess、clean函数已定义
data = pd.read_csv('wikihowAll.csv')
data = data.dropna()
data['clean_title'] = data['title'].map(lambda s: preprocess(s))
data['clean_headline'] = data['headline'].map(lambda s: preprocess(s))
data['clean_text'] = data['text'].map(lambda s: preprocess(s))
data['clean_title'] = data['clean_title'].astype(str)
data['clean_headline'] = data['clean_headline'].astype(str)
data['clean_text'] = data['clean_text'].astype(str)
data['title_clean_sent'] = data['title'].apply(clean)
data['headline_clean_sent'] = data['headline'].apply(clean)
data['text_clean_sent'] = data['text'].apply(clean)
data = data[['clean_title','headline_clean_sent','text_clean_sent']]
data.columns = ['tag', 'patterns', 'responses']
data['tag'] = data['tag'].astype(str)
data['patterns'] = data['patterns'].astype(str)
data['responses'] = data['responses'].astype(str)

# 直接构造符合后续处理要求的intents字典
intents_dict = {
    "intents": data.to_dict(orient='records')
}

# 正确写入JSON文件:将Python字典直接序列化为JSON
with open("myfile.json", "w") as outfile:
    json.dump(intents_dict, outfile, indent=2)

# 读取并解析JSON文件
data_file = open('myfile.json').read()
intents = json.loads(data_file)

# 后续处理逻辑保持不变
words = []
documents = []
classes = []

for intent in intents['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'])

关键修改点

  • 直接构造目标结构:用data.to_dict(orient='records')将DataFrame转为记录列表,再包裹为{"intents": ...}的字典,完全匹配后续代码的访问逻辑。
  • 避免重复序列化:使用json.dump(intents_dict, outfile)直接将Python字典序列化为JSON写入文件,解决了原代码中字符串嵌套的问题。
  • 保持后续逻辑不变:读取后intents为预期的字典结构,intents['intents']可正确获取所有意图列表,遍历无错误。

验证有效性

  1. 检查JSON文件结构:打开myfile.json,确认内容为标准JSON格式,顶层是含intents键的字典,值为所有记录的数组。
  2. 运行代码:不再触发TypeError,顺利完成分词、语料文档构建与类别收集。
  3. 对接ChatBot训练:确保后续基于Transformers的训练流程可正常读取该数据集。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 04:53:15