Python jieba库的使用

坚持是一种品质 2019-11-03

jieba库是Python中对中文分词效果比较好的一个库,最近正好看到MOOC上嵩天老师的课程,因此也跟着学了下

首先肯定需要安装jieba ,这个很简单,win+r cmd下运行以下代码即可,但是由于PY第三方库很多是国外源提供,速度比较慢,因此可能会出现报错等情况

pip install jieba

 新手们可以和我一样使用这样的方式来改善下载慢容易报错的位置,等学到LINUX系统前后基本上就知道解决方式了,目前可以在C:\Users\xxx(你的用户名)下新建一个pip文件夹,里边新建一个pip.ini文件,以记事本方式打开,里边粘贴进去以下代码即可

[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple

这样之后的pip即可使用指定的源安装,速度会相对较快,国内用的比较多的还有豆瓣源,感兴趣的可以百度搜一下,将网址指定为豆瓣源的网址即可

之后可以开始编写,我自己写的代码如下,没有完全参照嵩天老师的代码:

import  jieba
filename = ‘D:\pychram\sanguoyanyi.txt‘
with open(filename,‘r‘,encoding="UTF-8") as f:
    txt = f.read()
    fenhao = jieba.lcut(txt)
counts = {}
for word in fenhao:
    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(15):
    word,count =items[i]
    print("\n人物:{},出现共计:{}次".format(word,count))

 输出结果为

人物:曹操,出现共计:939次

人物:孔明,出现共计:831次

人物:将军,出现共计:746次

人物:却说,出现共计:647次

人物:玄德,出现共计:570次

人物:丞相,出现共计:489次

人物:关公,出现共计:484次

人物:二人,出现共计:464次

人物:不可,出现共计:430次

人物:荆州,出现共计:413次

人物:孔明曰,出现共计:384次

人物:玄德曰,出现共计:383次

人物:不能,出现共计:381次

人物:如此,出现共计:375次

人物:张飞,出现共计:349次

Process finished with exit code 0

里边有几个例如孔明,孔明曰等其实为同一人,但分成了两组,然后如此不能之类的则不是人名,其实没达到我们的要求,因此需要对jieba的分词进行设置
删除其中的却说等等,并且将孔明,孔明曰整合

import  jieba
filename = ‘D:\pychram\sanguoyanyi.txt‘
with open(filename,‘r‘,encoding="UTF-8") as f:
    txt = f.read()
    fenhao = jieba.lcut(txt)

counts = {}
for word in fenhao:
    if len(word) == 1:
        continue
    elif word =="诸葛亮" or word == "孔明曰":
        trueword == "孔明"
    elif word =="关公" or word == "云长":
        trueword == "关羽"
    elif word == "玄德" or word == "玄德曰":
        trueword == "刘备"
    elif word == "孟德" or word == "丞相":
        trueword == "曹操"
    else:
        trueword = word
        counts[trueword] = counts.get(trueword,0)+1
s = {"将军","却说","荆州","二人","不可","不能","如此"}
for wrong in s:
    del counts[wrong]
items = list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
for i in range(15):
    word,count =items[i]
    print("\n人物:{},出现共计:{}次".format(word,count))

但其实这样还是会有新的非人名词汇出现,输出结果为

Building prefix dict from the default dictionary ...
Loading model from cache C:\Users\oslo\AppData\Local\Temp\jieba.cache
Loading model cost 0.602 seconds.
Prefix dict has been built succesfully.

人物:曹操,出现共计:939次

人物:孔明,出现共计:831次

人物:张飞,出现共计:349次

人物:商议,出现共计:343次

人物:如何,出现共计:336次

人物:主公,出现共计:327次

人物:军士,出现共计:310次

人物:吕布,出现共计:302次

人物:左右,出现共计:290次

人物:军马,出现共计:287次

人物:引兵,出现共计:276次

人物:刘备,出现共计:272次

人物:次日,出现共计:269次

人物:大喜,出现共计:265次

人物:孙权,出现共计:262次

Process finished with exit code 0

之后可以将大喜,次日等加入S集合,删掉,再不断优化,即可得到出场次序

相关推荐