python - 无法从函数附加值
问题描述
我编写了一个函数来评估句子中a 列中的情绪dataframedata_tweets['text']
:消极,积极或中性态度,我尝试将输出附加到列表中,因为我想将情绪添加到原始数据框中
我的功能:
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
# function to print sentiments
# of the sentence.
def sentiment_scores(sentence):
# Create a SentimentIntensityAnalyzer object.
sid_obj = SentimentIntensityAnalyzer()
# polarity_scores method of SentimentIntensityAnalyzer
# oject gives a sentiment dictionary.
# which contains pos, neg, neu, and compound scores.
sentiment_dict = sid_obj.polarity_scores(sentence)
print("Sentence Overall Rated As",end = " ")
# decide sentiment as positive, negative and neutral
if sentiment_dict['compound'] >= 0.05 :
print("Positive")
elif sentiment_dict['compound'] <= - 0.05 :
print("Negative")
else :
print("Neutral")
输出:
Neutral
Neutral
Positive
Neutral
Neutral
这是我为追加列表而写的内容,但是当我打印时tweet_sentiment_vader
,我只得到None
. 谁能告诉我为什么我不能成功地将值附加到一个空列表?
tweet_sentiment_vader = []
row_count=data_tweets.shape[0]
for i in range(row_count):
sent = data_tweets['text'][i]
tweet_sentiment_vader.append(sentiment_scores(sent))
解决方案
尝试构建并返回一个列表:
def sentiment_scores(sentence):
local_tweet_sentiment_vader = []
# Create a SentimentIntensityAnalyzer object.
sid_obj = SentimentIntensityAnalyzer()
# polarity_scores method of SentimentIntensityAnalyzer
# oject gives a sentiment dictionary.
# which contains pos, neg, neu, and compound scores.
sentiment_dict = sid_obj.polarity_scores(sentence)
print("Sentence Overall Rated As",end = " ")
# decide sentiment as positive, negative and neutral
if sentiment_dict['compound'] >= 0.05 :
print("Positive")
local_tweet_sentiment_vader.append("Positive")
elif sentiment_dict['compound'] <= - 0.05 :
print("Negative")
local_tweet_sentiment_vader.append("Negative")
else :
print("Neutral")
local_tweet_sentiment_vader.append("Neutral")
return local_tweet_sentiment_vader
打印语句不会被附加到列表中
推荐阅读
- java - 我正在尝试安装 IBM Control Desk
- typescript - 如何强制类为函数成员实现具有正确类型签名的接口
- vue.js - vue-custom 指令调用方法
- powerapps - Powerapps - 将列(输入文本框)动态添加到表中
- javascript - 将 if 添加到 FullCalendar 中的事件
- python - 如何在 html 文档中使用 for 循环
- flutter - 嵌套 GestureDetector OnTap 函数
- sql - 如何在 sequlize 中将字段分组为数组?
- c++ - 如何忽略对 libpangocairo 库的未定义引用
- android - 如何冻结 ImageView 图像