jieba是优秀的中文分词第三方库
jieba库的安装
在cmd命令行使用pip工具: pip install jieba
jieba分词的原理
jieba分词依靠中文词库
- 利用一个中文词库,确定中文字符之间的关联概率
- 中文字符间概率大的组成词组,形成分词结果
- 除了分词,用户还可以添加自定义的词组
jieba分词的三种模式
- 精确模式:把文本精确的切分开,不存在冗余单词
- 全模式:把文本中所有可能的词语都扫描出来,有冗余
- 搜索引擎模式:在精确模式基础上,对长词再次切分
jieba库常用函数
实例:文本词频统计
- 需求:一篇文章,出现了哪些词?哪些词出现得最多?
- 该怎么做呢?
英文文本 中文文本
问题分析:
- 英文文本: Hamet 分析词频
https://python123.io/resources/pye/hamlet.txt - 中文文本:《三国演义》 分析人物
https://python123.io/resources/pye/threekingdoms.txt
打开链接,将页面另存到本地文档即可(当然,对于其他文档的词频分析也是如此)
代码实现:
- 英文文本: 《哈姆雷特》 分析词频
#CalHamlet
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 #使用字典表达词频
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))
#关于代码语句的理解:
for word in words:
counts[word] = counts.get(word,0)+1
#字典类型的counts.get(word,0)方法表示:若word在counts中则返回word对应的值,若不在则返回0. 等价于如下代码:
if word in counts:
counts[word] = counts[word] + 1
else:
counts[word] = 1
- 中文文本:《三国演义》 分析人物
jieba分析中,本是同一人的不同称呼会被划分到不同类别,对此,设置个excludes集合来将此区分合并统计
import jieba
txt = open("threekingdoms.txt","r",encoding="utf-8").read()
excludes = {"将军","却说","荆州","二人","不可","不能","如此"}
words = jieba.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))
拓展学习
- 《红楼梦》、《西游记》、《水浒传》…
- 政府工作报告、科研论文、新闻报道 …
- 还可结合词云…
- …
实践出真知,自己去动手,去思考,去拓展吧!!!
这里再提供一下官网的详细说明文档:https://github.com/fxsjy/jieba