Mandrek Mandrek -4 years ago 55
Python Question

How to write sentiment analysis results from twitter into a CSV file

I am new to python and NLP , i am working on twitter sentiment analysis.i am able to print the data along with the polarity and subjectivity also but my goal is to write the data to a csv file which i am not able to do, i am getting IO exception while doing that . Here is my code

import tweepy
from textblob import TextBlob
import csv

consumer_key = 'xxxxxxxxxxxxxxxxxxxxxx'
consumer_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

access_token = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
access_token_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'

auth = tweepy.OAuthHandler(consumer_key,consumer_secret)
auth.set_access_token(access_token,access_token_secret)

api = tweepy.API(auth)

public_tweets = api.search('Uk election')
with open("sentiment.txt",'w') as scorefile:
scoreFileWriter = csv.writer(scorefile)
for tweet in public_tweets:
print(tweet.text)
analysis = TextBlob(tweet.text)
print(analysis.sentiment)
scoreFileWriter.writerow([tweet.text,analysis.sentiment])


I am getting exception as ,

Traceback (most recent call last):
File "C:/Users/Jeet Chatterjee/NLP/sentiment_analysis_twitter.py", line 25, in <module>
scoreFileWriter.writerow([tweet.text,analysis.sentiment])
ValueError: I/O operation on closed file.


i just want to have 3 columns like polarity , subjectivity and the content in the csv file . Please help

Answer Source

Indentation is really important in python otherwise your blocks are considerered empty. In your case the with block ends immediately and thus the file is closed which is why you get this exception.

The code should probably look like this:

public_tweets = api.search('Uk election')
with open("sentiment.txt",'w') as scorefile:
    scoreFileWriter = csv.writer(scorefile) 
    for tweet in public_tweets:
        print(tweet.text)
        analysis = TextBlob(tweet.text)
        print(analysis.sentiment)
        scoreFileWriter.writerow([tweet.text,analysis.sentiment])
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download