【问题标题】:list index out of range error with TextBlob to csv使用 TextBlob 到 csv 的列表索引超出范围错误
【发布时间】:2018-09-29 23:22:37
【问题描述】:

我的博客中有一个包含数千个 cmets 的大型 csv,我想对使用 textblob 和 nltk 进行情绪分析。

我正在使用来自https://wafawaheedas.gitbooks.io/twitter-sentiment-analysis-visualization-tutorial/sentiment-analysis-using-textblob.html 的 python 脚本,但针对 Python3 进行了修改。

'''
uses TextBlob to obtain sentiment for unique tweets
'''

from importlib import reload
import csv
from textblob import TextBlob
import sys

# to force utf-8 encoding on entire program
#sys.setdefaultencoding('utf8')

alltweets = csv.reader(open("/path/to/file.csv", 'r', encoding="utf8", newline=''))
sntTweets = csv.writer(open("/path/to/outputfile.csv", "w", newline=''))

for row in alltweets:
    blob = TextBlob(row[2])
    print (blob.sentiment.polarity)
    if blob.sentiment.polarity > 0:
        sntTweets.writerow([row[0], row[1], row[2], row[3], blob.sentiment.polarity, "positive"])
    elif blob.sentiment.polarity < 0:
        sntTweets.writerow([row[0], row[1], row[2], row[3], blob.sentiment.polarity, "negative"])
    elif blob.sentment.polarity == 0.0:
        sntTweets.writerow([row[0], row[1], row[2], row[3], blob.sentiment.polarity, "neutral"])

但是,当我运行它时,我不断得到

    $ python3 sentiment.py
Traceback (most recent call last):
  File "sentiment.py", line 17, in <module>
    blob = TextBlob(row[2])
IndexError: list index out of range

我知道错误的含义,但我不确定我需要做些什么来修复。

对我缺少的东西有什么想法吗?谢谢!

【问题讨论】:

  • 您的输入文件中的列似乎少于 3 列。请检查是否是这种情况。
  • if len(row) &lt; 3: continue ?
  • @YoavAbadi 我的输入 csv 只有一列。我会先尝试添加两个空列
  • @YoavAbadi 这对我有所帮助,但后来我一直遇到奇怪的输出格式问题。我提供了一个最终有效的答案 - 使用 pandas
  • @BearBrown 这不太奏效。但我最终找到了一个在此处发布的解决方案。谢谢!

标签: python csv nlp textblob


【解决方案1】:

玩了一会之后,我想出了一个更优雅的解决方案,使用 pandas

from textblob import TextBlob
import pandas as pd

df = pd.read_csv("pathtoinput.csv", na_values='', 
encoding='utf8',keep_default_na=False, low_memory=False)

columns = ['text']

df = df[columns]

df['tweet'] = df['text'].astype('str')

df['polarity'] = df['tweet'].apply(lambda tweet: 
TextBlob(tweet).sentiment.polarity)

df.loc[df.polarity > 0, 'sentiment'] ='positive'
df.loc[df.polarity == 0, 'sentiment'] ='neutral'
df.loc[df.polarity < 0, 'sentiment'] ='negative'

df.to_csv("pathtooutput.csv", encoding='utf-8', index=False)

【讨论】:

    猜你喜欢
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多