首页 > 解决方案 > 无法从函数附加值

问题描述

我编写了一个函数来评估句子中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))

标签: pythonlist

解决方案


尝试构建并返回一个列表:

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

打印语句不会被附加到列表中


推荐阅读