Search code examples
pythoncsvnlptextblob

list index out of range error with TextBlob to csv


I have a large csv with thousands of comments from my blog that I'd like to do sentiment analysis on using textblob and nltk.

I'm using the python script from https://wafawaheedas.gitbooks.io/twitter-sentiment-analysis-visualization-tutorial/sentiment-analysis-using-textblob.html, but modified for 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"])

However, when I run this, I continually get

    $ 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

I know what the error means, but I'm not sure what I need to do to fix.

Any thoughts on what I'm missing? Thanks!


Solution

  • After playing around a bit, I figured out a more elegant solution for this using 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)