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 '!@#$%^&*()_-+=`~:;"/?>.<,|\\':
        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

猜你喜欢

转载自blog.csdn.net/qq_25672165/article/details/85055628
今日推荐