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

Python处理JSON日期转换时遇list indices类型错误求助

解决列表索引错误与DataFrame转JSON的正确方式

报错原因

list indices must be integers or slices, not str 说明你循环中的tweet是列表类型,而非预期的字典,所以无法用字符串键(如"created_at")进行索引。这大概率是JSON文件的结构不符合预期,或者读取方式有误导致的。


1. 正确使用DataFrame转JSON

orient='records'是完全正确的选择——它会将DataFrame的每一行转为一个独立字典,最终生成的JSON是字典组成的数组,完美匹配你代码中tweet_list的结构需求。

转存代码示例:

# 假设你的DataFrame名为df
df.to_json('tweets.json', orient='records', indent=2)

2. 正确读取JSON文件

确保读取后得到的是字典列表,而非嵌套列表:

import json

with open('tweets.json', 'r', encoding='utf-8') as f:
    tweet_list = json.load(f)

执行后可以打印tweet_list[0]验证,输出应该是包含created_at、text等键的字典。

3. 修复代码中的变量名错误

你的代码里存在一处变量名误用:find_sentiment(text)应该改为find_sentiment(full_text),因为你处理后的文本变量是full_text:

counts = {}

for tweet in tweet_list:
    date = datetime.strftime(datetime.strptime(tweet["created_at"],'%a %b %d %H:%M:%S +0000 %Y'), '%Y-%m-%d')
    if date not in counts:
        counts[date] = dict(sentiments=list(), tweet_count = 0) 
    counts[date]["tweet_count"] += 1
    full_text = cleanTxt(tweet["text"])
    # 修正变量名:传入full_text而非text
    counts[date]["sentiments"].append(find_sentiment(full_text))

关于orient='index'的问题

orient='index'会将DataFrame的行索引作为JSON的键,因此必然会包含行号,这不符合你的业务需求,所以直接放弃该选项即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 00:45:37