jieba是優秀的中文分詞第三方庫
jieba庫的安裝
在cmd命令行使用pip工具: pip install jieba
jieba分詞的原理
jieba分詞依靠中文詞庫
- 利用一箇中文詞庫,確定中文字符之間的關聯概率
- 中文字符間概率大的組成詞組,形成分詞結果
- 除了分詞,用戶還可以添加自定義的詞組
jieba分詞的三種模式
- 精確模式:把文本精確的切分開,不存在冗餘單詞
- 全模式:把文本中所有可能的詞語都掃描出來,有冗餘
- 搜索引擎模式:在精確模式基礎上,對長詞再次切分
jieba庫常用函數
實例:文本詞頻統計
- 需求:一篇文章,出現了哪些詞?哪些詞出現得最多?
- 該怎麼做呢?
英文文本 中文文本
問題分析:
- 英文文本: Hamet 分析詞頻
https://python123.io/resources/pye/hamlet.txt - 中文文本:《三國演義》 分析人物
https://python123.io/resources/pye/threekingdoms.txt
打開鏈接,將頁面另存到本地文檔即可(當然,對於其他文檔的詞頻分析也是如此)
代碼實現:
- 英文文本: 《哈姆雷特》 分析詞頻
#CalHamlet
def getText():
txt = open("hamlet.txt","r").read() #打開文檔
txt = txt.lower() #將文檔內容全部轉爲小寫字母
for ch in '!"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
txt = txt.replace(ch," ") #將文本中特殊字符替換爲空格
return txt
hamletTxt = getText()
words = hamletTxt.split()
counts = {} #文本去噪及歸一化
for word in words:
counts[word] = counts.get(word,0)+1 #使用字典表達詞頻
items = list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
for i in range(10):
word,count = items[i]
print("{0:<10}{1:>5}".format(word,count))
#關於代碼語句的理解:
for word in words:
counts[word] = counts.get(word,0)+1
#字典類型的counts.get(word,0)方法表示:若word在counts中則返回word對應的值,若不在則返回0. 等價於如下代碼:
if word in counts:
counts[word] = counts[word] + 1
else:
counts[word] = 1
- 中文文本:《三國演義》 分析人物
jieba分析中,本是同一人的不同稱呼會被劃分到不同類別,對此,設置個excludes集合來將此區分合並統計
import jieba
txt = open("threekingdoms.txt","r",encoding="utf-8").read()
excludes = {"將軍","卻說","荊州","二人","不可","不能","如此"}
words = jieba.lcut(txt)
counts = {}
for word in words:
if len(word) == 1:
continue
elif word == "諸葛亮" or word == "孔明曰":
rword = "孔明"
elif word == "關公" or word == "雲長":
rword = "關羽"
elif word == "玄德" or word == "玄德曰":
rword = "劉備"
elif word == "孟德" or word == "丞相":
rword = "曹操"
else:
rword = word
counts[rword] = counts.get(rword,0)+1
for word in excludes:
del counts[word]
items = list(counts.items()) #中文文本分詞
items.sort(key=lambda x:x[1],reverse=True)
for i in range(10): #使用字典表達詞頻
word,count = items[i]
print("{0:<10}{1:>5}".format(word,count))
拓展學習
- 《紅樓夢》、《西遊記》、《水滸傳》…
- 政府工作報告、科研論文、新聞報道 …
- 還可結合詞雲…
- …
實踐出真知,自己去動手,去思考,去拓展吧!!!
這裏再提供一下官網的詳細說明文檔:https://github.com/fxsjy/jieba