user11952178
user11952178

Reputation:

Why cant I get my output dataframe to convert to a csv? AttributeError: 'NoneType' object has no attribute 'to_csv'

import pandas as pd
import csv
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer

with open('Before.csv', "r", errors='ignore') as f:
    reader = csv.reader(f)
    your_list = list(reader)

analyser = SentimentIntensityAnalyzer()

def print_sentiment_scores(alist):
    for aSentence in alist: 
      aSnt = analyser.polarity_scores(aSentence[0])
      print(str(aSnt))

print_sentiment_scores(your_list)

My output reprex is:

{'neg': 0.0, 'neu': 0.492, 'pos': 0.508, 'compound': 0.4754}
{'neg': 0.0, 'neu': 0.367, 'pos': 0.633, 'compound': 0.7845}
{'neg': 0.0, 'neu': 0.691, 'pos': 0.309, 'compound': 0.8004}
{'neg': 0.0, 'neu': 0.462, 'pos': 0.538, 'compound': 0.5413}
{'neg': 0.0, 'neu': 0.636, 'pos': 0.364, 'compound': 0.7906}

so I did df_before = print_sentiment_scores(your_list)

and then df_before.to_csv("df_Before_sentiment.csv")

But I received an error AttributeError: 'NoneType' object has no attribute 'to_csv'. How can I convert my ouput of print_sentiment_scores(your_list) to a csv in a dataframe format so all values show under each header like neg,neu,pos,compound?

Upvotes: 0

Views: 3010

Answers (2)

fiveobjects
fiveobjects

Reputation: 4269

As I mentioned in the comment to the original post, you have to return either a dict or an array or DataFrame from print_sentiment_scores() function.

I suggest the following change to create a DataFrame and return from print_sentiment_scores() function:

def print_sentiment_scores(alist):
    df = pd.DataFrame();
    for aSentence in alist: 
      aSnt = analyser.polarity_scores(aSentence[0])
      df = df.append(aSnt, ignore_index=True)
      print(str(aSnt))

    return df

And then call to_csv() on the returned DataFrame:

df_before = print_sentiment_scores(your_list)
print(df_before.to_csv())

Upvotes: 1

ruhaib
ruhaib

Reputation: 649

you need to fix your print_sentiment_scores like this:

def print_sentiment_scores(alist):
    polarity_scores = []
    for aSentence in alist: 
        aSnt = analyser.polarity_scores(aSentence[0])
        print(str(aSnt))
        polarity_scores += [aSnt]

    return polarity_scores

which will return the following list:

[
    {'neg': 0.0, 'neu': 0.492, 'pos': 0.508, 'compound': 0.4754},
    {'neg': 0.0, 'neu': 0.367, 'pos': 0.633, 'compound': 0.7845},
    {'neg': 0.0, 'neu': 0.691, 'pos': 0.309, 'compound': 0.8004},
    {'neg': 0.0, 'neu': 0.462, 'pos': 0.538, 'compound': 0.5413},
    {'neg': 0.0, 'neu': 0.636, 'pos': 0.364, 'compound': 0.7906}
]

finally, this will generate the required csv:

output_df = DataFrame(print_sentiment_scores(your_list))
output_df.to_csv('some_name.csv')

Upvotes: 1

Related Questions