溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python利用多種方式來統(tǒng)計(jì)詞頻(單詞個(gè)數(shù))

發(fā)布時(shí)間:2020-09-16 06:05:24 來源:腳本之家 閱讀:229 作者:Sinte-Beuve 欄目:開發(fā)技術(shù)

python的思維就是讓我們用盡可能少的代碼來解決問題。對于詞頻的統(tǒng)計(jì),就代碼層面而言,實(shí)現(xiàn)的方式也是有很多種的。之所以單獨(dú)談到統(tǒng)計(jì)詞頻這個(gè)問題,是因?yàn)樗诮y(tǒng)計(jì)和數(shù)據(jù)挖掘方面經(jīng)常會用到,尤其是處理分類問題上。故在此做個(gè)簡單的記錄。

統(tǒng)計(jì)的材料如下:

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來進(jìn)行統(tǒng)計(jì)(遍歷+循環(huán))

word_count = {}
for word in document:
  if word in word_count:
    word_count[word] += 1
 else:
    word_count[word] = 1

更優(yōu)雅的實(shí)現(xiàn)方式

#假如字典中不存在給定的鍵,則返回參數(shù)中提供的默認(rèn)值;反之,則返回字典中保存的值。
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來實(shí)現(xiàn)

# 使用collections中的defalutdict來實(shí)現(xiàn),defalutdict是一種值可以默認(rèn)設(shè)置的dict
from collections import defaultdict
word_count = defaultdict(int)
for word in document:
  word_count[word] += 1

使用Counter

word_counter = Counter(document)

Counter既然是一個(gè)計(jì)數(shù)器,那么它本身也就具有很多統(tǒng)計(jì)的方法。例如,最常見的詞頻統(tǒng)計(jì)的排序,可以獲得前n個(gè)最高的詞頻。

# 返回前n個(gè)最高詞頻,以字典的形式
word_counter.most_common(n)

顯然,使用defalutdict和Counter代碼最簡潔,更能符合python開發(fā)之道。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI