python利用多種方式來統(tǒng)計詞頻(單詞個數(shù))
python的思維就是讓我們用盡可能少的代碼來解決問題。對于詞頻的統(tǒng)計,就代碼層面而言,實現(xiàn)的方式也是有很多種的。之所以單獨談到統(tǒng)計詞頻這個問題,是因為它在統(tǒng)計和數(shù)據(jù)挖掘方面經(jīng)常會用到,尤其是處理分類問題上。故在此做個簡單的記錄。
統(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文件操作中進行字符串替換的方法(保存到新文件/當前文件)
這篇文章主要介紹了Python文件操作中進行字符串替換的方法(保存到新文件/當前文件) ,本文給大家介紹兩種方法,每種方法給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2019-06-06
基于Django?websocket實現(xiàn)視頻畫面的實時傳輸功能(最新推薦)
Django?Channels?是一個用于在?Django框架中實現(xiàn)實時、異步通信的擴展庫,本文給大家介紹基于Django?websocket實現(xiàn)視頻畫面的實時傳輸案例,本案例是基于B/S架構的視頻監(jiān)控畫面的實時傳輸,使用django作為服務端的開發(fā)框架,需要的朋友可以參考下2023-06-06
Python2和Python3中urllib庫中urlencode的使用注意事項
這篇文章主要介紹了Python2和Python3中urllib庫中urlencode的使用注意事項,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-11-11
Python使用擴展庫pywin32實現(xiàn)批量文檔打印實例
這篇文章主要介紹了Python使用擴展庫pywin32實現(xiàn)批量文檔打印實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04

