前言
本文的文字及圖片來源于網路,僅供學習、交流使用,不具有任何商業用途,如有問題請及時聯系我們以作處理,
以下文章來源于快學Python ,作者小小明
Python爬蟲、資料分析、網站開發等案例教程視頻免費在線觀看
https://space.bilibili.com/523606542
資料準備
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])
結果:
216435 ['天龍', '釋名', '青衫', '磊落', '險峰', '行玉壁', '月華', '明馬', '疾香', '幽崖', '高遠', '微步', '生家', '子弟', '家院', '計悔情', '虎嘯', '龍吟', '換巢', '鸞鳳']
統計詞頻排名前N的詞
原始字典自寫代碼統計:
wordcount = {} for word in all_words: wordcount[word] = wordcount.get(word, 0)+1 sorted(wordcount.items(), key=lambda x: x[1], reverse=True)[:10]
結果:
使用計數類進行詞頻統計:
from collections import Counter wordcount = Counter(all_words) wordcount.most_common(10)
結果:
使用pandas進行詞頻統計:
pd.Series(all_words).value_counts().head(10)
結果:
從上面的結果可以看到使用collections的Counter類來計數會更快一點,而且編碼也最簡單,
分詞程序中直接統計詞頻
Pandas只能對已經分好的詞統計詞頻,所以這里不再演示,上面的測驗表示,Counter直接對串列進行計數比pyhton原生帶快,但回圈中的表現還未知,下面再繼續測驗一下,
首先使用原生API直接統計詞頻并排序:
%%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])
結果:
[('段譽', 2496), ('說道', 2151), ('虛竹', 1633), ('蕭峰', 1301), ('武功', 1095), ('阿紫', 922), ('阿朱', 904), ('喬峰', 900), ('王語嫣', 877), ('慕容復', 871)] Wall time: 6.04 s
下面我們使用Counter統計詞頻并排序:
%%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))
結果:
[('段譽', 2496), ('說道', 2151), ('虛竹', 1633), ('蕭峰', 1301), ('武功', 1095), ('阿紫', 922), ('阿朱', 904), ('喬峰', 900), ('王語嫣', 877), ('慕容復', 871)] Wall time: 6.21 s
可以看到Counter在回圈中計數時反而慢了一丁點,但由于Counter類整體性能更佳,撰寫起來簡單,所以一般都用Counter進行統計計數,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/248867.html
標籤:Python

