1. 程式人生 > >09.4 python基礎--jieba庫

09.4 python基礎--jieba庫

09.4.1 簡介

jieba庫是優秀的中文分詞第三方庫
jieba庫提供三種分詞模式,最簡單隻需掌握一個函式

原理:利用一箇中文詞庫,確定漢字之間的關聯概率

09.4.2 分詞的三種模式

精確模式:把文字精確的切分開,不存在冗餘單詞
全模式:把文字中所有可能的詞語都掃描出來,有冗餘
搜尋引擎模式:在精確模式基礎上,對長詞再次切分

09.4.3 常用庫函式

分詞要點:jieba.lcut(s)
##精確模式,返回一個列表型別的分詞結果
a=jieba.lcut( "中國是一個偉大的國家");print(a)
>['中國', '是', '一個', '偉大', '的', '國家']

##全模式,返回一個列表型別的分詞結果,存在冗餘
b=jieba.lcut( "中國是一個偉大的國家",cut_all=True);print(b)
>['中國', '國是', '一個', '偉大', '的', '國家']

##搜尋引擎模式,返回一個列表型別的分詞結果,存在冗餘
c=jieba.lcut_for_search("中華人民共和國是偉大的");print(c)
>['中華', '華人', '人民', '共和', '共和國', '中華人民共和國', '是', '偉大', '的']

##向分詞詞典增加新詞(兩種方式)
jieba.add_word('我愛')
jieba.load_userdict('1.txt')

09.4.4 程式碼

hamlet中字元出現次數

def getText():      ##文字轉換統一
    txt = open('C:/Users/ZY/Desktop/hamlet.txt','r').read()   ##讀取檔案
    txt = txt.lower()                ##轉換為小寫
    for o in '[email protected]#$%^&*()_-+=`~:;"/?>.<,|\\':
        txt =txt.replace(o,' ')   ## 替換特殊符號為空字元
    return txt

HamltTxt = getText()     ##呼叫轉換後的函式
words =HamltTxt.split()    ##按照空格拆分
counts = {}       ## 字典
for word in words:
    counts[word] = counts.get(word,0) + 1 ## 字典的get()方法計算出現次數
items = list(counts.items())    ##  將字典的每一個鍵值對當作一項轉化為列表
items.sort(key = lambda x:x[1],reverse=True)  ## 排序後倒排
for i in range(10):
    word, count = items[i]  ##取前10位
    print('{0:<10}{1:>5}'.format(word,count))
print(items)

>the 1138
 and 965
 to 752
 of 669
 you 550
 i 542
 a 542
 my 514
 hamlet 462
 in 436
>[('the', 1138), ('and', 965), ('to', 752), ('of', 669), ('you', 550), ('i', 542),.....

三國演義

import jieba
txt = open('C:/Users/ZY/Desktop/sanguo.txt','r',encoding ='utf-8').read()
words = jieba.lcut(txt)
counts={}
for word in words:
    if len(word)==1:
        continue
    else:
        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))

>呂布 180
 曹操 140
 董卓 104
 將軍 101
 玄德 98
 卻說 73
 天下 66
 孫策 65
 徐州 61
 袁紹 60