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

Python文本情感分析预测时出现IndexError下标越界错误如何解决

问题原因

  • 报错核心是你用的tweet行索引和pred预测结果数组的长度不匹配,触发数组越界:
    1. tokenizer.texts_to_sequences()要求传入文本列表,你直接传入单条字符串row时,方法会把字符串拆成单个字符分别处理,返回的序列长度等于该条文本的字符数,对应model.predict()返回的pred数组第一维长度就是字符数,远小于你从iteritems()拿到的整条tweet的索引值(比如你处理第54条tweet,pred长度只有48,取pred[54]自然越界)。
    2. 二分类模型的predict()返回值结构一般为(样本数, 1),你直接用行索引取对应位置的数值逻辑本身就不成立。

修复方案

按照以下调整代码即可解决:

  1. 给单条文本套上列表,符合texts_to_sequences的输入要求
  2. 直接取第一条预测结果的第一个数值作为当前tweet的情感分数,不要用外层行索引取值
  3. 补充必要的资源释放逻辑、优化写文件效率

修复后代码

import json
import pandas as pd

# 外层文件操作改用with语句自动管理资源
with open("/content/trending_tweets.json", "r+", encoding='utf-8') as f:
    data = f.read()

for x in data.split("\n"):
    if not x.strip(): # 跳过空行避免json解析错误
        continue
    strlist = "[" + x + "]"
    datalist = json.loads(strlist)
    for y in datalist:
        # 追加写入用户数据也用with管理
        with open('/content/user_lookup_data.json', 'a', encoding='utf-8') as f:
            # 此处如果有写入需求可自行补充f.write逻辑
            pass
        print(y["user"]["screen_name"])
        screen_name = '@' + y["user"]["screen_name"]
        file_name = f'/content/user_timeline/{screen_name}_tweets.csv'
        user_timeline_data = pd.read_csv(file_name, sep='\t', lineterminator='\n', encoding='latin')
        user_timeline_data = user_timeline_data['tweet']
        print(len(user_timeline_data))
        df = pd.DataFrame(columns=['Text', 'Sentiment'])
        for index, row in user_timeline_data.iteritems():
            # 单条文本套列表,符合输入要求
            sequence = tokenizer.texts_to_sequences([row])
            test = pad_sequences(sequence, maxlen=max_len)
            pred = model.predict(test)
            # 直接取第一个样本的预测值
            if pred[0][0] > 0.5:
                df.loc[index, ['Text']] = row
                df.loc[index, ['Sentiment']] = 'Positive'
            else:
                df.loc[index, ['Text']] = row
                df.loc[index, ['Sentiment']] = 'Negative'
            print(df.shape)
            print(pred)
        # 全量处理完再写文件,避免频繁IO
        df.to_csv(f'sentiment_{screen_name}.csv', index=False)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 01:36:04