2017-09-07 40 views
-1

我正在嘗試編寫一個函數,該函數將佔用一行文本並返回前5個最常見的單詞。如果兩個相同的單詞具有相同的頻率,則按照字母順序將其返回。使用從收藏櫃檯:Python:在文本行中返回5個最常見的

def top5_words(text): 
    top5 = {} 
    freq = Counter(text.split()).most_common(5) 
    for i in freq: 
     top5[i[0]] = i[1] 
    return sorted(top5.items())[:5] 

它確實返回[('a', 1), ('one', 3), ('racehorse', 1), ('two', 2), ('was', 2)]但我想通過單詞返回它。例如:['one', 'two', 'was', 'a', 'racehorse']

回答

0

most_common()已經爲了歸還物品,所以:

def top5_words(text): 
    freq = Counter(text.split()).most_common(5) 
    return [word for word, _ in freq] 

會做你想要什麼。

相關問題