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(your_list)
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')
