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

Python使用NLTK清洗CSV评论数据报列表索引类型错误如何解决

报错原因
  • 遍历逻辑错误:for i in mylist 中 i 直接是mylist里的评论文本字符串,不是列表索引,用字符串作为下标访问列表元素不符合Python语法,就会触发对应TypeError。
  • 结果存储逻辑错误:原代码中new_lists.append(mylist)是把整个列表重复追加到新容器,无法得到单条清洗后的评论结果。
  • 符号转义错误:代码里的"是HTML转义字符,需替换为正常的英文引号才能正常运行。
修复后完整代码
import pandas as pd
import nltk 
nltk.download('words')
words = set(nltk.corpus.words.words())

uscomment = r'C:\Users\John\Desktop\us_final_dataset.csv'
df = pd.read_csv(uscomment)
mylist = df['us_comment'].tolist()
new_lists = []

# 遍历逻辑调整,直接取每条评论处理
for comment in mylist:
    # 增加非字符串判断,避免空值/异常值报错
    if not isinstance(comment, str):
        new_lists.append("")
        continue
    cleaned = " ".join(w for w in nltk.wordpunct_tokenize(comment) if w.lower() in words or not w.isalpha())
    new_lists.append(cleaned)

# 处理结果写入原数据表导出为新CSV
df['cleaned_comment'] = new_lists
df.to_csv(r'C:\Users\John\Desktop\cleaned_us_final_dataset.csv', index=False, encoding='utf-8-sig')
注意事项
  • 导出的CSV会保留原所有字段,新增cleaned_comment列存储清洗后的评论内容,可根据需求调整导出字段
  • 如果需要过滤掉清洗后为空的评论,导出前可添加df = df[df['cleaned_comment'].str.strip() != '']过滤
  • NLTK的英文词库仅包含通用英文词汇,部分专有名词、网络热词会被误过滤,有对应需求可以自定义词库补充到words集合中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.18 22:06:02