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)


我的输出代表是:

{'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}


所以我做了df_before = print_sentiment_scores(您的清单)

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


但是我收到一个错误AttributeError:'NoneType'对象没有属性'to_csv'。如何将我的print_sentiment_scores(your_list)的输出转换为数据帧格式的csv,以便所有值都显示在每个标题下,例如neg,neu,pos,compound?

最佳答案

您需要像这样修复您的print_sentiment_scores:

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


这将返回以下列表:

[
    {'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}
]


最后,这将生成所需的csv:

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

关于python - 为什么我无法将输出数据帧转换为csv? AttributeError:“NoneType”对象没有属性“to_csv”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57579268/

10-11 00:55