image.png
jieba
“結巴”中文分詞:做最好的 Python 中文分詞組件
“Jieba” (Chinese for “to stutter”) Chinese text segmentation: built to be the best Python Chinese word segmentation module.
GitHub: https://github.com/fxsjy/jieba
支持三種分詞模式:
- 精確模式,試圖將句子最精確地切開,適合文本分析;
- 全模式,把句子中所有的可以成詞的詞語都掃描出來, 速度非常快,但是不能解決歧義;
- 搜索引擎模式,在精確模式的基礎上,對長詞再次切分,提高召回率,適合用于搜索引擎分詞。
- 支持繁體分詞
- 支持自定義詞典
- MIT 授權協議
安裝
pip install jieba
image.png
驗證是否安裝成功:
image.png
導入成功,說明成功安裝了。O(∩_∩)O
使用說明
jieba分詞的三種模式
- 精確模式:把文本精確的切分開,不存在冗余單詞
- 全模式:把文本中所有可能的詞語都掃描出來,有冗余
- 搜索引擎模式:在精確模式基礎上,對長詞再次切分
常用API函數
image.png
實戰
# -*- coding: utf-8 -*-
import jieba
seg_str = "曾慮多情損梵行,入山又恐別傾城,世間安得雙全法,不負如來不負卿。"
print("/".join(jieba.lcut(seg_str))) # 精簡模式,返回一個列表類型的結果
print("/".join(jieba.lcut(seg_str, cut_all=True))) # 全模式,使用 'cut_all=True' 指定
print("/".join(jieba.lcut_for_search(seg_str))) # 搜索引擎模式
運行效果:
image.png
計算下慶余年頻率最高的詞語
# -*- coding: utf-8 -*-
import jieba
txt = open("./慶余年.txt", "r", encoding='utf-8').read()
# 精簡模式
words = jieba.lcut(txt)
# 使用key-value形式保存記錄詞語出現的次數
counts = {}
for word in words:
# 排除長度為1的漢字詞語
if len(word) == 1:
continue
else:
# 查詢key值并對其對應的value值+1
counts[word] = counts.get(word, 0) + 1
items = list(counts.items())
# 排序
items.sort(key=lambda x: x[1], reverse=True)
# 列出前十個詞語
for i in range(50):
word, count = items[i]
print("{0:<5}{1:>5}".format(word, count))
注意:如果打開文檔報錯,需要講文檔轉換成utf-8格式保存后,再次打開
運行結果:
image.png
范閑不愧是豬腳。O(∩_∩)O