MENU

jieba库使用实例

December 30, 2018 • Read: 8874 • python阅读设置

jieba库概述

jieba是优秀的中文分词第三方库

jieba库安装

windows下cmd命令行

pip install jieba

jieba分词的原理

jieba分词依靠中文词库,确定中文字符之间的关联概率。中文字符间概率大的组成词组,形成分词结果

除了分词,用户还可以添加自定义词组

jieba库的使用

jieba分词的三种模式

  • 精确模式:把文本精确的分开,不存在冗余单词
  • 全模式:把文本中所有可能的词语都扫描出来,有冗余
  • 搜索引擎模式:在精确模式的基础上,对长词再次切分

jieba库常用函数

函数描述
jieba.lcut(s)精确模式,返回一个列表类型的分词结果
jieba.lcut(s, cut_all=True)全模式,返回一个列表类型的分词结果,存在冗余
jieba.lcut_for_search全模式,返回一个列表类型的分词结果,存在冗余
jieba.add_word(w)向分词词典增加新词w

文本词频统计

Hamlet英文词频统计

#Hamlet.py
def getText():
    txt = open("hamlet.txt","r").read()
    txt = txt.lower()
    for ch in '|"#$%&()*+,-./:;<=>?@[\\]^_‘{|}~':
        txt = txt.replace(ch," ")
    return txt
    
hamletTxt = getText()
words = hamletTxt.split()
counts = {}
for word in words:
    counts[word] = counts.get(word,0) + 1 #get(key[,default])
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))

首先读取文本,将其中的一些英文符号替换为空格(文本去噪)

然后是split()方法,他将字符串以空格和换行拆分为多个子字符串返回一个list类型

字典的get方法格式为get(key[,default]),通过key获取value,如果没有找到key则使用默认值default

items = list(counts.items())返回的是一个list,list中包含多个将key和value封装起来的tuple类型的数据

最后输出次数最高的前十个单词以及词频

the        1138
and         965
to          754
of          668
you         549
a           542
i           540
my          514
hamlet      456
in          436

《三国演义》任务出场统计

#ThreeKingdomsV1.py
from jieba import *
txt = open("threekingdoms.txt","r",encoding = "utf-8").read()
words = 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(15):
    word, count = items[i]
    print("{0:<10}{1:>5}".format(word, count))

运行结果如下:

曹操          953
孔明          836
将军          772
却说          656
玄德          585
关公          510
丞相          491
二人          469
不可          440
荆州          425
玄德曰         390
孔明曰         390
不能          384
如此          378
张飞          358

从结果中发现一些问题,“孔明”和“孔明曰”都代表孔明,“玄德”和“玄德曰”也代表同一个人,因此还需要对程序进行优化。

首先增加一个excludes列表,里面存放一些需要排除的关键字,比方说从上面的结果发现“二人”,“不能”,“如此”等一些词并不是人名,所以我们将这些词添加进excludes列表,在统计完结果之后,将列表中key在excludes列表中的词都删掉

对于表示同一个人的说法,比方说“玄德”和“玄德曰”,我们可以给其赋一个新的key,叫“刘备”。再比如“诸葛亮”和“孔明曰”,我们给其赋新的key叫“孔明”

优化后的代码如下:

#ThreeKingdomsV2.py
from jieba import *
txt = open("threekingdoms.txt","r",encoding = "utf-8").read()
excludes = {"将军","却说","荆州","二人","不可","不能","如此","如何","商议","左右","军马","一人","次日","引兵","大喜","军士","天下","东吴","于是","今日","不敢","魏兵"}
words = lcut(txt)
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 == "孟德" or word == "丞相":
        rword = "曹操"
    else:
        rword = word
    counts[rword] = counts.get(rword,0) + 1
for word in excludes:
    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))

运行结果如下:

曹操         1451
孔明         1383
刘备         1252
关羽          784
张飞          358
主公          331
吕布          300
赵云          278
孙权          264
陛下          223

常见问题

在使用jieba库的时候,如果读取的是文本中的内容,必须要设置文本的编码格式为UTF-8,否则会报错

Last Modified: January 1, 2019
Archives Tip
QR Code for this page
Tipping QR Code
Leave a Comment

2 Comments
  1. 朱文骁 朱文骁

    这个好像在脚本之间的微信公众号看过

    1. mathor mathor

      @朱文骁@(呵呵)我是在mooc上学的