jieba 庫(kù)是優(yōu)秀的中文分詞第三方庫(kù),中文文本需要通過分詞獲得單個(gè)的詞語
成都創(chuàng)新互聯(lián)主營(yíng)勐海網(wǎng)站建設(shè)的網(wǎng)絡(luò)公司,主營(yíng)網(wǎng)站建設(shè)方案,成都App制作,勐海h5成都小程序開發(fā)搭建,勐海網(wǎng)站營(yíng)銷推廣歡迎勐海等地區(qū)企業(yè)咨詢
管理員身份運(yùn)行cmd窗口輸入命令:pip install jieba
lcut 將返回的對(duì)象轉(zhuǎn)化為 list 對(duì)象返回
該方法適合用于搜索引擎構(gòu)建倒排索引的分詞,顆粒度較細(xì)
jieba.lcut_for_search 方法返回列表類型
開發(fā)者可以指定自己自定義的詞典,以便包含jieba詞庫(kù)里沒有的詞。雖然jieba有新詞識(shí)別能力,但是自行添加新詞可以保證更高的正確率
sentence 為待提取的文本
topK 為返回幾個(gè)TF/IDF權(quán)重最大的關(guān)鍵詞,默認(rèn)是20
jieba.posseg.dt 為默認(rèn)詞性標(biāo)注分詞器
標(biāo)注句子分詞后每個(gè)詞的詞性,采用和ictclas兼容的標(biāo)記法
import jieba
list1 = jieba.lcut("中華人民共和國(guó)是一個(gè)偉大的國(guó)家")
print(list1)
print("精確模式:"+"/".join(list1))
list2 = jieba.lcut("中華人民共和國(guó)是一個(gè)偉大的國(guó)家",cut_all = True)
print(list2,end=",")
print("全模式:"+"/".join(list2))
list3 = jieba.lcut_for_search("中華人民共和國(guó)是一個(gè)偉大的國(guó)家")
print(list3)
print("搜索引擎模式:"+" ".join(list3))
import jieba
text = "中信建投投資公司了一款游戲,中信也投資了一個(gè)游戲公司"
word = jieba.lcut(text)
print(word)
# 添加詞
jieba.add_word("中信建投")
jieba.add_word("投資公司")
word1 = jieba.lcut(text)
print(word1)
# 刪除詞
jieba.del_word("中信建投")
word2 = jieba.lcut(text)
print(word2)
import jieba.posseg as pseg
words = pseg.cut("我愛北京天安門")
for i in words:
print(i.word,i.flag)
三國(guó)演義文本下載
import jieba
txt = open("文件路徑", "r", encoding='utf-8').read() # 打開并讀取文件
words = jieba.lcut(txt) # 使用精確模式對(duì)文本進(jìn)行分詞
counts = {} # 通過鍵值對(duì)的形式存儲(chǔ)詞語及其出現(xiàn)的次數(shù)
for word in words:
if len(word) == 1: # 單個(gè)詞語不計(jì)算在內(nèi)
continue
else:
counts[word] = counts.get(word, 0) + 1 # 遍歷所有詞語,每出現(xiàn)一次其對(duì)應(yīng)的值加 1
items = list(counts.items()) #將鍵值對(duì)轉(zhuǎn)換成列表
items.sort(key=lambda x: x[1], reverse=True) # 根據(jù)詞語出現(xiàn)的次數(shù)進(jìn)行從大到小排序
for i in range(15):
word, count = items[i]
print("{0:<10}{1:>5}".format(word, count))
import jieba
excludes = {"將軍","卻說","荊州","二人","不可","不能","如此","如何"}
txt = open("三國(guó)演義.txt", "r", encoding='utf-8').read()
words = jieba.lcut(txt)
counts = {}
for word in words:
if len(word) == 1:
continue
elif word == "諸葛亮" or word == "孔明曰":
rword = "孔明"
elif word == "關(guān)公" or word == "云長(zhǎng)":
rword = "關(guān)羽"
elif word == "玄德" or word == "玄德曰":
rword = "劉備"
elif word == "孟德" or word == "丞相":
rword = "曹操"
else:
rword = word
counts[rword] = counts.get(rword,0) + 1
for i in excludes:
del counts[i]
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))