2016-10-27 52 views
-1

我想使用我以前的函數calculate_total_sentiment(tweet1):它將推文排序到不同類別的"very positive", "positive", "neutral, "negative""very negative"調用str的另一個函數列表到新的函數列表

現在我想要使用這個新函數group_by_sentiment它需要一個字符串列表,我想將它們分類在與我的calculate_total_sentiment相同的類別中。

我如何將它們整理出來?下面是我的代碼calculate_total_sentiment哪些作品,我想弄清楚如何實現這個功能,並將其分類到相同的類別。

group_by_sentiment

例子是

group_by_sentiment(['sad', '#notok']) 
    [[], [], [], [], ['sad', 'notok']] 

其中最後名單將包含所有的非常不利的類別,而首先是非常積極的

def calculate_total_sentiment(tweet1): 
    total = negative_word_score(tweet) + positive_word_score(tweet) + \ 
    positive_hashtag_score(tweet) + negative_hashtag_score(tweet) + \ 
    emoticon_score(tweet) 
    if total > 2: 
     return ("Very Positive") 
    elif total > 0: 
     return ("Positive") 
    elif total == 0: 
     return ("Neutral") 
    elif total > -3: 
     return ("Negative") 
    else: 
     return ("Very Negative") 


def group_by_sentiment(L): 
    very_negative = [] 
    negative = [] 
    neutral = [] 
    positive = [] 
    very_positive = [] 
    output = [very_positive, positive, neutral, negative, very_negative] 
    for char in range(len(L)): 
     if calculate_total_sentiment(tweet1) == 'Very Positive': 
      output[0].append(very_positive) 
     elif calculate_total_sentiment(tweet1) == 'Positive': 
      output[1].append(positive) 
     elif calculate_total_sentiment(tweet1) == 'Neutral': 
      output[2].append(neutral) 
     elif calculate_total_sentiment(tweet1) == 'Negative': 
      output[3].append(negative) 
     elif calculate_total_sentiment(tweet1) == 'Very Negative': 
      output[4].append(very_negative) 
    return output 

回答

0

我不知道我理解你的問題完全,但是有沒有任何理由你沒有使用字典(或者是這個特殊情況下defaultdict):

from collections import defaultdict 
def group_by_sentiment(L): 
    output = defaultdict(list) 
    for tweet in L: 
     output[calculate_total_sentiment(tweet)].append(tweet)] 
    return output 
>>> group_by_sentiment(['sad', '#notok']) 
defaultdict(list, {'Very Negative': ['sad', '#notok']}) 

你顯然有一些其他問題與您的代碼像tweetcalculate_total_sentiment被定義,因爲ARG被稱爲tweet1

+0

這是因爲calculate_total_sentiment是在我以前的功能,它調用的函數,它們都加起來然後在calculate_total_sentiment中總結出一定的數字。我嘗試了該功能的多個例子,它的工作原理。但是,只是這種將字符串列表分類到列表列表中的新功能無法正常工作,但我不知道我出錯的地方以及如何修復它。 – naruto321

+0

也試圖按照group_by_sentiment中列表的特定順序對它們進行排序第一個列表[[0] [1] [2] [3] [4]]都是非常積極的分類已calculate_total_sentiment將去那裏等 – naruto321

+0

對不起,然後我幫不了你。我不明白你的問題,你顯然有一個具體的實施。 – AChampion