利用多種方式來統計詞頻(單詞個數)
python的思維就是讓我們用盡可能少的代碼來解決問題。對於詞頻的統計,就代碼層面而言,實現的方式也是有很多種的。之所以單獨談到統計詞頻這個問題,是因為它在統計和數據挖掘方面經常會用到,尤其是處理分類問題上。故在此做個簡單的記錄。
統計的材料如下:
document = [
'look', 'into', 'my', 'eyes', 'look', 'into', 'my', 'eyes',
'the', 'eyes', 'the', 'eyes', 'the', 'eyes', 'not', 'around', 'the',
'eyes', "don't", 'look', 'around', 'the', 'eyes', 'look', 'into',
'my', 'eyes', "you're", 'under']
- 直接使用dict來進行統計(遍歷+循環)
word_count = {}
for word in document:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
- 更優雅的實現方式
#假如字典中不存在給定的鍵,則返回參數中提供的默認值;反之,則返回字典中保存的值。
for word in document:
previous_count = word_count.get(word, 0)
word_count[word] = previous_count + 1
#可以合並成一行
for word in document:
word_count[word] = word_count.setdefault(word, 0) + 1
- 使用defalutdict來實現
# 使用collections中的defalutdict來實現,defalutdict是一種值可以默認設置的dict
from collections import defaultdict
word_count = defaultdict(int)
for word in document:
word_count[word] += 1
- 使用Counter
word_counter = Counter(document)
Counter既然是一個計數器,那么它本身也就具有很多統計的方法。例如,最常見的詞頻統計的排序,可以獲得前n個最高的詞頻。
# 返回前n個最高詞頻,以字典的形式
word_counter.most_common(n)
顯然,使用defalutdict和Counter代碼最簡潔,更能符合python開發之道。
