jieba庫的使用及實例


安裝:

  cmd模式下輸入

pip install jieba

  anaconda對應環境

conda install jieba

分詞原理:

   Jieba分詞依靠中文詞庫

    -利用一個中文詞庫,確定漢字之間的關聯概率

    -漢字間概率大的組成詞組,形成分詞結果

    -除了分詞,用戶還可以添加自定義的詞組

jieba庫的三種模式:

  -精確模式:把文本精確的切分開,不存在冗余單詞

#jieba.lcut(s)
jieba.lcut("中國是一個偉大的國家")

#output:['中國', '是', '一個', '偉大', '的', '國家']  

  -全模式:把文本中所有的可能的詞語都掃描出來,有冗余  

#jieba.lcut(s,cut_all=True)
jieba.lcut("中國是一個偉大的國家",cut_all=True)

#output:['中國', '國是', '一個', '偉大', '的', '國家']   

  -全搜索引擎模式:在精確模式的基礎上,對長詞再次切分

#jieba.lcut_for_search(s)
jieba.lcut_for_search("中華人民共和國是偉大的")

#output:['中華', '華人', '人民', '共和', '共和國', '中華人民共和國', '是', '偉大', '的']

 

向分詞詞典中增加新詞w:

#jieba.add_word(w)

jieba.add_word("蟒蛇語言")



 
        
#CalThreeKingdomsV2.py

#統計三國人物出場頻率  url='https://python123.io/resources/pye/threekingdoms.txt'
import jieba, requests

def getText():
    #下載到本地,或者直接爬下來
    #txt = open('threekingdoms.txt','r',encoding= 'utf-8').read()
    try:
        re = requests.get(url='https://python123.io/resources/pye/threekingdoms.txt',timeout=30)
        re.raise_for_status()           #如果狀態不是200引發HTTPError異常
        re.encoding = re.apparent_encoding
        return re.text
    except:
        return ''

#剔除非名字 
excludes = {"將軍",'卻說','荊州','二人','不可','軍馬','引兵','次日','大喜',
            '不能','如此','商議','如何','軍士','左右','\r\n'}

words = jieba.lcut(getText())

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:
        rword = '曹操'
    else:
        rword = word
    counts[rword] = counts.get(rword,0)+1
for word in excludes:
    if word in counts:
        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))
 
        

(learn) D:\pycodes>python CalThreeKingdomsV2.py
Building prefix dict from the default dictionary ...
Loading model from cache C:\Users\hao11\AppData\Local\Temp\jieba.cache
Loading model cost 0.625 seconds.
Prefix dict has been built successfully.
孔明         1383
劉備         1252
曹操          960
關羽          784
丞相          491
張飛          358
主公          331
呂布          300
趙雲          278
孫權          264

有許多地方可以優化,丞相和主公這類詞,可以特殊處理。

jieba.lcut("淡黃的長裙,蓬松的頭發")
['淡黃', '的', '長裙', ',', '蓬松', '的', '頭發']
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM