19

结巴分词快速入门指南

 4 years ago
source link: https://foofish.net/jieba.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

结巴分词是Python语言中最流行的一个分词工具,本文将介绍结巴分词快速入门使用

安装

pip install jieba

简单分词

import jieba

result = jieba.cut("我爱中国北京大学")
for word in result:
    print(word)

输出

我
爱
中国
北京大学

句子切分成了5个词组。

全模式分词

result = jieba.cut("我爱中国北京大学", cut_all=True)
for word in result:
    print(word)

输出

我
爱
中国
北京
北京大学
大学

全模式分出来的词覆盖面更广。

提取关键词

从一个句子或者一个段落中提取前k个关键词

import jieba.analyse

result = jieba.analyse.extract_tags("机器学习,需要一定的数学基础,需要掌握的数学基础知识特别多,"
                                    "如果从头到尾开始学,估计大部分人来不及,我建议先学习最基础的数学知识",
                                    topK=5,
                                    withWeight=False)
import pprint

pprint.pprint(result)

输出

['数学', '学习', '数学知识', '基础知识', '从头到尾']
  • topK 为返回前topk个权重最大的关键词
  • withWeight 返回每个关键字的权重值

去掉停止词

停止词是指在句子中无关紧要的词语,例如标点符号、指示代词等等,做分词前要先将这些词去掉。分词方法 cut 不支持直接过滤停止词,需要手动处理。提取关键字的方法 extract_tags 支持停止词过滤

# 先过滤停止词
jieba.analyse.set_stop_words(file_name) 
result = jieba.analyse.extract_tags(content, tokK)

file_name 的文件格式是文本文件,每行一个词语

官方地址:https://github.com/fxsjy/jieba

有问题可以扫描二维码和我交流

关注公众号「Python之禅」,回复「1024」免费获取Python资源

vQremuy.jpg!web

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK