python利用多種方式來統(tǒng)計詞頻(單詞個數(shù))
python的思維就是讓我們用盡可能少的代碼來解決問題。對于詞頻的統(tǒng)計,就代碼層面而言,實現(xiàn)的方式也是有很多種的。之所以單獨談到統(tǒng)計詞頻這個問題,是因為它在統(tǒng)計和數(shù)據挖掘方面經常會用到,尤其是處理分類問題上。故在此做個簡單的記錄。
統(tǒng)計的材料如下:
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來進行統(tǒng)計(遍歷+循環(huán))
word_count = {}
for word in document:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
更優(yōu)雅的實現(xiàn)方式
#假如字典中不存在給定的鍵,則返回參數(shù)中提供的默認值;反之,則返回字典中保存的值。 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來實現(xiàn)
# 使用collections中的defalutdict來實現(xiàn),defalutdict是一種值可以默認設置的dict from collections import defaultdict word_count = defaultdict(int) for word in document: word_count[word] += 1
使用Counter
word_counter = Counter(document)
Counter既然是一個計數(shù)器,那么它本身也就具有很多統(tǒng)計的方法。例如,最常見的詞頻統(tǒng)計的排序,可以獲得前n個最高的詞頻。
# 返回前n個最高詞頻,以字典的形式 word_counter.most_common(n)
顯然,使用defalutdict和Counter代碼最簡潔,更能符合python開發(fā)之道。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Python利用pandas和matplotlib實現(xiàn)繪制柱狀折線圖
這篇文章主要為大家詳細介紹了如何使用?Python?中的?Pandas?和?Matplotlib?庫創(chuàng)建一個柱狀圖與折線圖結合的數(shù)據可視化圖表,感興趣的可以了解一下2023-11-11
Python運維自動化psutil模塊的監(jiān)控和管理深入探究
這篇文章主要為大家介紹了Python運維自動化psutil模塊的監(jiān)控和管理深入探究,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01

