image.png
“结巴”中文分词:做最好的 Python 中文分词组件
“Jieba” (Chinese for “to stutter”) Chinese text segmentation: built to be the best Python Chinese word segmentation module.
GitHub: https://github.com/fxsjy/jieba
pip install jieba
image.png
验证是否安装成功:
image.png
导入成功,说明成功安装了。O(∩_∩)O
jieba分词的三种模式
image.png
# -*- coding: utf-8 -*-
import jieba
seg_str = "曾虑多情损梵行,入山又恐别倾城,世间安得双全法,不负如来不负卿。"
print("/".join(jieba.lcut(seg_str))) # 精简模式,返回一个列表类型的结果
print("/".join(jieba.lcut(seg_str, cut_all=True))) # 全模式,使用 'cut_all=True' 指定
print("/".join(jieba.lcut_for_search(seg_str))) # 搜索引擎模式
运行效果:
image.png
# -*- coding: utf-8 -*-
import jieba
txt = open("./庆余年.txt", "r", encoding='utf-8').read()
# 精简模式
words = jieba.lcut(txt)
# 使用key-value形式保存记录词语出现的次数
counts = {}
for word in words:
# 排除长度为1的汉字词语
if len(word) == 1:
continue
else:
# 查询key值并对其对应的value值+1
counts[word] = counts.get(word, 0) + 1
items = list(counts.items())
# 排序
items.sort(key=lambda x: x[1], reverse=True)
# 列出前十个词语
for i in range(50):
word, count = items[i]
print("{0:<5}{1:>5}".format(word, count))
注意:如果打开文档报错,需要讲文档转换成utf-8格式保存后,再次打开
运行结果:
image.png