溫馨提示×

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

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

Python中怎么實(shí)現(xiàn)詞頻統(tǒng)計(jì)功能

發(fā)布時(shí)間:2021-08-11 14:47:00 來源:億速云 閱讀:706 作者:Leah 欄目:大數(shù)據(jù)

這篇文章將為大家詳細(xì)講解有關(guān)Python中怎么實(shí)現(xiàn)詞頻統(tǒng)計(jì)功能,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對(duì)相關(guān)知識(shí)有一定的了解。

數(shù)據(jù)準(zhǔn)備

import jieba

with open("D:/hdfs/novels/天龍八部.txt", encoding="gb18030") as f:
    text = f.read()
with open('D:/hdfs/novels/names.txt', encoding="utf-8") as f:
    for line in f:
        if line.startswith("天龍八部"):
            names = next(f).split()
            break

for word in names:
    jieba.add_word(word)

#  加載停用詞
with open("stoplist.txt", encoding="utf-8-sig") as f:
    stop_words = f.read().split()
stop_words.extend(['天龍八部', '\n', '\u3000', '目錄', '一聲', '之中', '只見'])
stop_words = set(stop_words)
all_words = [word for word in cut_word if len(word) > 1 and word not in stop_words]
print(len(all_words), all_words[:20])

結(jié)果:

216435 ['天龍', '釋名', '青衫', '磊落', '險(xiǎn)峰', '行玉壁', '月華', '明馬', '疾香', '幽崖', '高遠(yuǎn)', '微步', '生家', '子弟', '家院', '計(jì)悔情', '虎嘯', '龍吟', '換巢', '鸞鳳']

統(tǒng)計(jì)詞頻排名前N的詞

原始字典自寫代碼統(tǒng)計(jì):

wordcount = {}
for word in all_words:
    wordcount[word] = wordcount.get(word, 0)+1
sorted(wordcount.items(), key=lambda x: x[1], reverse=True)[:10]

使用計(jì)數(shù)類進(jìn)行詞頻統(tǒng)計(jì):

from collections import Counter

wordcount = Counter(all_words)
wordcount.most_common(10)

結(jié)果:

Python中怎么實(shí)現(xiàn)詞頻統(tǒng)計(jì)功能

使用pandas進(jìn)行詞頻統(tǒng)計(jì):

pd.Series(all_words).value_counts().head(10)

分詞過程中直接統(tǒng)計(jì)詞頻

Pandas只能對(duì)已經(jīng)分好的詞統(tǒng)計(jì)詞頻,所以這里不再演示。上面的測(cè)試表示,Counter直接對(duì)列表進(jìn)行計(jì)數(shù)比pyhton原生帶快,但循環(huán)中的表現(xiàn)還未知,下面再繼續(xù)測(cè)試一下。

首先使用原生API直接統(tǒng)計(jì)詞頻并排序:

%%time
wordcount = {}
for word in jieba.cut(text):
    if len(word) > 1 and word not in stop_words:
        wordcount[word] = wordcount.get(word, 0)+1
print(sorted(wordcount.items(), key=lambda x: x[1], reverse=True)[:10])

結(jié)果:

[('段譽(yù)', 2496), ('說道', 2151), ('虛竹', 1633), ('蕭峰', 1301), ('武功', 1095), ('阿紫', 922), ('阿朱', 904), ('喬峰', 900), ('王語嫣', 877), ('慕容復(fù)', 871)]
Wall time: 6.04 s

下面我們使用Counter統(tǒng)計(jì)詞頻并排序:

%%time
wordcount = Counter()
for word in jieba.cut(text):
    if len(word) > 1 and word not in stop_words:
        wordcount[word] += 1
print(wordcount.most_common(10))

結(jié)果:

[('段譽(yù)', 2496), ('說道', 2151), ('虛竹', 1633), ('蕭峰', 1301), ('武功', 1095), ('阿紫', 922), ('阿朱', 904), ('喬峰', 900), ('王語嫣', 877), ('慕容復(fù)', 871)]
Wall time: 6.21 s

關(guān)于Python中怎么實(shí)現(xiàn)詞頻統(tǒng)計(jì)功能就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

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

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

AI