大数据,机器学习,人工智能人工智能/模式识别/机器学习精华专题人工智能(语言识别&图像识别)

python jieba分词库使用

2020-04-20  本文已影响0人  Lee_5566
image.png

jieba

“结巴”中文分词:做最好的 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分词的三种模式

常用API函数

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

范闲不愧是猪脚。O(∩_∩)O

参考

pypi
实例解析:Python jieba库用法(具有不错的参考价值)

上一篇 下一篇

猜你喜欢

热点阅读