jieba
“结巴”中文分词:做最好的 Python 中文分词组件
"Jieba" (Chinese for "to stutter") Chinese text segmentation: built to be the best Python Chinese word segmentation module.
支持三种分词模式:
支持繁体分词
http://jiebademo.ap01.aws.af.cm/
(Powered by Appfog)
网站代码:https://github.com/fxsjy/jiebademo
代码对 Python 2/3 均兼容
easy_install jieba
或者 pip install jieba
/ pip3 install jieba
python setup.py install
import jieba
来引用jieba.cut
方法接受三个输入参数: 需要分词的字符串;cut_all 参数用来控制是否采用全模式;HMM 参数用来控制是否使用 HMM 模型jieba.cut_for_search
方法接受两个参数:需要分词的字符串;是否使用 HMM 模型。该方法适合用于搜索引擎构建倒排索引的分词,粒度比较细jieba.cut
以及 jieba.cut_for_search
返回的结构都是一个可迭代的 generator,可以使用 for 循环来获得分词后得到的每一个词语(unicode),或者用jieba.lcut
以及 jieba.lcut_for_search
直接返回 listjieba.Tokenizer(dictionary=DEFAULT_DICT)
新建自定义分词器,可用于同时使用不同词典。jieba.dt
为默认分词器,所有全局分词相关函数都是该分词器的映射。代码示例
# encoding=utf-8
import jieba
seg_list = jieba.cut("我来到北京清华大学", cut_all=True)
print("Full Mode: " + "/ ".join(seg_list)) # 全模式
seg_list = jieba.cut("我来到北京清华大学", cut_all=False)
print("Default Mode: " + "/ ".join(seg_list)) # 精确模式
seg_list = jieba.cut("他来到了网易杭研大厦") # 默认是精确模式
print(", ".join(seg_list))
seg_list = jieba.cut_for_search("小明硕士毕业于中国科学院计算所,后在日本京都大学深造") # 搜索引擎模式
print(", ".join(seg_list))
输出:
【全模式】: 我/ 来到/ 北京/ 清华/ 清华大学/ 华大/ 大学
【精确模式】: 我/ 来到/ 北京/ 清华大学
【新词识别】:他, 来到, 了, 网易, 杭研, 大厦 (此处,“杭研”并没有在词典中,但是也被Viterbi算法识别出来了)
【搜索引擎模式】: 小明, 硕士, 毕业, 于, 中国, 科学, 学院, 科学院, 中国科学院, 计算, 计算所, 后, 在, 日本, 京都, 大学, 日本京都大学, 深造
dict.txt
一样,一个词占一行;每一行分三部分:词语、词频(可省略)、词性(可省略),用空格隔开,顺序不可颠倒。file_name
若为路径或二进制方式打开的文件,则文件必须为 UTF-8 编码。例如:
创新办 3 i
云计算 5
凱特琳 nz
台中
更改分词器(默认为 jieba.dt
)的 tmp_dir
和 cache_file
属性,可分别指定缓存文件所在的文件夹及其文件名,用于受限的文件系统。
范例:
自定义词典:https://github.com/fxsjy/jieba/blob/master/test/userdict.txt
用法示例:https://github.com/fxsjy/jieba/blob/master/test/test_userdict.py
之前: 李小福 / 是 / 创新 / 办 / 主任 / 也 / 是 / 云 / 计算 / 方面 / 的 / 专家 /
加载自定义词库后: 李小福 / 是 / 创新办 / 主任 / 也 / 是 / 云计算 / 方面 / 的 / 专家 /
add_word(word, freq=None, tag=None)
和 del_word(word)
可在程序中动态修改词典。使用 suggest_freq(segment, tune=True)
可调节单个词语的词频,使其能(或不能)被分出来。
注意:自动计算的词频在使用 HMM 新词发现功能时可能无效。
代码示例:
>>> print('/'.join(jieba.cut('如果放到post中将出错。', HMM=False)))
如果/放到/post/中将/出错/。
>>> jieba.suggest_freq(('中', '将'), True)
494
>>> print('/'.join(jieba.cut('如果放到post中将出错。', HMM=False)))
如果/放到/post/中/将/出错/。
>>> print('/'.join(jieba.cut('「台中」正确应该不会被切开', HMM=False)))
「/台/中/」/正确/应该/不会/被/切开
>>> jieba.suggest_freq('台中', True)
69
>>> print('/'.join(jieba.cut('「台中」正确应该不会被切开', HMM=False)))
「/台中/」/正确/应该/不会/被/切开
"通过用户自定义词典来增强歧义纠错能力" --- https://github.com/fxsjy/jieba/issues/14
import jieba.analyse
代码示例 (关键词提取)
https://github.com/fxsjy/jieba/blob/master/test/extract_tags.py
关键词提取所使用逆向文件频率(IDF)文本语料库可以切换成自定义语料库的路径
关键词提取所使用停止词(Stop Words)文本语料库可以切换成自定义语料库的路径
关键词一并返回关键词权重值示例
算法论文: TextRank: Bringing Order into Texts
基本思想:
使用示例:
见 test/demo.py
jieba.posseg.POSTokenizer(tokenizer=None)
新建自定义分词器,tokenizer
参数可指定内部使用的jieba.Tokenizer
分词器。jieba.posseg.dt
为默认词性标注分词器。>>> import jieba.posseg as pseg
>>> words = pseg.cut("我爱北京天安门")
>>> for word, flag in words:
... print('%s %s' % (word, flag))
...
我 r
爱 v
北京 ns
天安门 ns
用法:
jieba.enable_parallel(4)
# 开启并行分词模式,参数为并行进程数jieba.disable_parallel()
# 关闭并行分词模式例子:https://github.com/fxsjy/jieba/blob/master/test/parallel/test_file.py
实验结果:在 4 核 3.4GHz Linux 机器上,对金庸全集进行精确分词,获得了 1MB/s 的速度,是单进程版的 3.3 倍。
注意:并行分词仅支持默认分词器 jieba.dt
和 jieba.posseg.dt
。
result = jieba.tokenize(u'永和服装饰品有限公司')
for tk in result:
print("word %s\t\t start: %d \t\t end:%d" % (tk[0],tk[1],tk[2]))
word 永和 start: 0 end:2
word 服装 start: 2 end:4
word 饰品 start: 4 end:6
word 有限公司 start: 6 end:10
result = jieba.tokenize(u'永和服装饰品有限公司', mode='search')
for tk in result:
print("word %s\t\t start: %d \t\t end:%d" % (tk[0],tk[1],tk[2]))
word 永和 start: 0 end:2
word 服装 start: 2 end:4
word 饰品 start: 4 end:6
word 有限 start: 6 end:8
word 公司 start: 8 end:10
word 有限公司 start: 6 end:10
from jieba.analyse import ChineseAnalyzer
用法示例:https://github.com/fxsjy/jieba/blob/master/test/test_whoosh.py
使用示例:python -m jieba news.txt > cut_result.txt
命令行选项(翻译):
使用: python -m jieba [options] filename
结巴命令行界面。
固定参数:
filename 输入文件
可选参数:
-h, --help 显示此帮助信息并退出
-d [DELIM], --delimiter [DELIM]
使用 DELIM 分隔词语,而不是用默认的' / '。
若不指定 DELIM,则使用一个空格分隔。
-p [DELIM], --pos [DELIM]
启用词性标注;如果指定 DELIM,词语和词性之间
用它分隔,否则用 _ 分隔
-D DICT, --dict DICT 使用 DICT 代替默认词典
-u USER_DICT, --user-dict USER_DICT
使用 USER_DICT 作为附加词典,与默认词典或自定义词典配合使用
-a, --cut-all 全模式分词(不支持词性标注)
-n, --no-hmm 不使用隐含马尔可夫模型
-q, --quiet 不输出载入信息到 STDERR
-V, --version 显示版本信息并退出
如果没有指定文件名,则使用标准输入。
--help
选项输出:
$> python -m jieba --help
Jieba command line interface.
positional arguments:
filename input file
optional arguments:
-h, --help show this help message and exit
-d [DELIM], --delimiter [DELIM]
use DELIM instead of ' / ' for word delimiter; or a
space if it is used without DELIM
-p [DELIM], --pos [DELIM]
enable POS tagging; if DELIM is specified, use DELIM
instead of '_' for POS delimiter
-D DICT, --dict DICT use DICT as dictionary
-u USER_DICT, --user-dict USER_DICT
use USER_DICT together with the default dictionary or
DICT (if specified)
-a, --cut-all full pattern cutting (ignored with POS tagging)
-n, --no-hmm don't use the Hidden Markov Model
-q, --quiet don't print loading messages to stderr
-V, --version show program's version number and exit
If no filename specified, use STDIN instead.
jieba 采用延迟加载,import jieba
和 jieba.Tokenizer()
不会立即触发词典的加载,一旦有必要才开始加载词典构建前缀字典。如果你想手工初始 jieba,也可以手动初始化。
import jieba
jieba.initialize() # 手动初始化(可选)
在 0.28 之前的版本是不能指定主词典的路径的,有了延迟加载机制后,你可以改变主词典的路径:
jieba.set_dictionary('data/dict.txt.big')
例子: https://github.com/fxsjy/jieba/blob/master/test/test_change_dictpath.py
占用内存较小的词典文件 https://github.com/fxsjy/jieba/raw/master/extra_dict/dict.txt.small
支持繁体分词更好的词典文件 https://github.com/fxsjy/jieba/raw/master/extra_dict/dict.txt.big
下载你所需要的词典,然后覆盖 jieba/dict.txt 即可;或者用 jieba.set_dictionary('data/dict.txt.big')
作者:piaolingxue 地址:https://github.com/huaban/jieba-analysis
作者:yanyiwu 地址:https://github.com/yanyiwu/cppjieba
作者:yanyiwu 地址:https://github.com/yanyiwu/nodejieba
作者:falood 地址:https://github.com/falood/exjieba
作者:qinwf 地址:https://github.com/qinwf/jiebaR
作者:yanyiwu 地址:https://github.com/yanyiwu/iosjieba
作者:fukuball 地址:https://github.com/fukuball/jieba-php
作者:anderscui 地址:https://github.com/anderscui/jieba.NET/
详见: https://github.com/fxsjy/jieba/issues/7
P(台中) < P(台)×P(中),“台中”词频不够导致其成词概率较低
解决方法:强制调高词频
jieba.add_word('台中')
或者 jieba.suggest_freq('台中', True)
解决方法:强制调低词频
jieba.suggest_freq(('今天', '天气'), True)
或者直接删除该词 jieba.del_word('今天天气')
解决方法:关闭新词发现
jieba.cut('丰田太省了', HMM=False)
jieba.cut('我们中出了一个叛徒', HMM=False)
更多问题请点击:https://github.com/fxsjy/jieba/issues?sort=updated&state=closed
https://github.com/fxsjy/jieba/blob/master/Changelog
"Jieba" (Chinese for "to stutter") Chinese text segmentation: built to be the best Python Chinese word segmentation module.
Support three types of segmentation mode:
Search Engine Mode, based on the Accurate Mode, attempts to cut long words into several short words, which can raise the recall rate. Suitable for search engines.
http://jiebademo.ap01.aws.af.cm/
(Powered by Appfog)
easy_install jieba
or pip install jieba
python setup.py install
after extracting.jieba
directory in the current directory or python site-packages
directory.import jieba
.jieba.cut
function accepts three input parameters: the first parameter is the string to be cut; the second parameter iscut_all
, controlling the cut mode; the third parameter is to control whether to use the Hidden Markov Model.jieba.cut_for_search
accepts two parameter: the string to be cut; whether to use the Hidden Markov Model. This will cut the sentence into short words suitable for search engines.jieba.cut
and jieba.cut_for_search
returns an generator, from which you can use a for
loop to get the segmentation result (in unicode).jieba.lcut
and jieba.lcut_for_search
returns a list.jieba.Tokenizer(dictionary=DEFAULT_DICT)
creates a new customized Tokenizer, which enables you to use different dictionaries at the same time. jieba.dt
is the default Tokenizer, to which almost all global functions are mapped.Code example: segmentation
#encoding=utf-8
import jieba
seg_list = jieba.cut("我来到北京清华大学", cut_all=True)
print("Full Mode: " + "/ ".join(seg_list)) # 全模式
seg_list = jieba.cut("我来到北京清华大学", cut_all=False)
print("Default Mode: " + "/ ".join(seg_list)) # 默认模式
seg_list = jieba.cut("他来到了网易杭研大厦")
print(", ".join(seg_list))
seg_list = jieba.cut_for_search("小明硕士毕业于中国科学院计算所,后在日本京都大学深造") # 搜索引擎模式
print(", ".join(seg_list))
Output:
[Full Mode]: 我/ 来到/ 北京/ 清华/ 清华大学/ 华大/ 大学
[Accurate Mode]: 我/ 来到/ 北京/ 清华大学
[Unknown Words Recognize] 他, 来到, 了, 网易, 杭研, 大厦 (In this case, "杭研" is not in the dictionary, but is identified by the Viterbi algorithm)
[Search Engine Mode]: 小明, 硕士, 毕业, 于, 中国, 科学, 学院, 科学院, 中国科学院, 计算, 计算所, 后, 在, 日本, 京都, 大学, 日本京都大学, 深造
jieba.load_userdict(file_name)
# file_name is a file-like object or the path of the custom dictionarydict.txt
: one word per line; each line is divided into three parts separated by a space: word, word frequency, POS tag. If file_name
is a path or a file opened in binary mode, the dictionary must be UTF-8 encoded.For example:
创新办 3 i
云计算 5
凱特琳 nz
台中
Change a Tokenizer's tmp_dir
and cache_file
to specify the path of the cache file, for using on a restricted file system.
Example:
云计算 5
李小福 2
创新办 3
[Before]: 李小福 / 是 / 创新 / 办 / 主任 / 也 / 是 / 云 / 计算 / 方面 / 的 / 专家 /
[After]: 李小福 / 是 / 创新办 / 主任 / 也 / 是 / 云计算 / 方面 / 的 / 专家 /
add_word(word, freq=None, tag=None)
and del_word(word)
to modify the dictionary dynamically in programs.Use suggest_freq(segment, tune=True)
to adjust the frequency of a single word so that it can (or cannot) be segmented.
Note that HMM may affect the final result.
Example:
>>> print('/'.join(jieba.cut('如果放到post中将出错。', HMM=False)))
如果/放到/post/中将/出错/。
>>> jieba.suggest_freq(('中', '将'), True)
494
>>> print('/'.join(jieba.cut('如果放到post中将出错。', HMM=False)))
如果/放到/post/中/将/出错/。
>>> print('/'.join(jieba.cut('「台中」正确应该不会被切开', HMM=False)))
「/台/中/」/正确/应该/不会/被/切开
>>> jieba.suggest_freq('台中', True)
69
>>> print('/'.join(jieba.cut('「台中」正确应该不会被切开', HMM=False)))
「/台中/」/正确/应该/不会/被/切开
import jieba.analyse
jieba.analyse.extract_tags(sentence, topK=20, withWeight=False, allowPOS=())
sentence
: the text to be extractedtopK
: return how many keywords with the highest TF/IDF weights. The default value is 20withWeight
: whether return TF/IDF weights with the keywords. The default value is FalseallowPOS
: filter words with which POSs are included. Empty for no filtering.jieba.analyse.TFIDF(idf_path=None)
creates a new TFIDF instance, idf_path
specifies IDF file path.Example (keyword extraction)
https://github.com/fxsjy/jieba/blob/master/test/extract_tags.py
Developers can specify their own custom IDF corpus in jieba keyword extraction
jieba.analyse.set_idf_path(file_name) # file_name is the path for the custom corpus
Developers can specify their own custom stop words corpus in jieba keyword extraction
jieba.analyse.set_stop_words(file_name) # file_name is the path for the custom corpus
There's also a TextRank implementation available.
Use: jieba.analyse.textrank(sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v'))
Note that it filters POS by default.
jieba.analyse.TextRank()
creates a new TextRank instance.
jieba.posseg.POSTokenizer(tokenizer=None)
creates a new customized Tokenizer. tokenizer
specifies the jieba.Tokenizer to internally use. jieba.posseg.dt
is the default POSTokenizer.>>> import jieba.posseg as pseg
>>> words = pseg.cut("我爱北京天安门")
>>> for w in words:
... print('%s %s' % (w.word, w.flag))
...
我 r
爱 v
北京 ns
天安门 ns
Usage:
jieba.enable_parallel(4)
# Enable parallel processing. The parameter is the number of processes.jieba.disable_parallel()
# Disable parallel processing.Example: https://github.com/fxsjy/jieba/blob/master/test/parallel/test_file.py
Result: On a four-core 3.4GHz Linux machine, do accurate word segmentation on Complete Works of Jin Yong, and the speed reaches 1MB/s, which is 3.3 times faster than the single-process version.
Note that parallel processing supports only default tokenizers, jieba.dt
and jieba.posseg.dt
.
result = jieba.tokenize(u'永和服装饰品有限公司')
for tk in result:
print("word %s\t\t start: %d \t\t end:%d" % (tk[0],tk[1],tk[2]))
word 永和 start: 0 end:2
word 服装 start: 2 end:4
word 饰品 start: 4 end:6
word 有限公司 start: 6 end:10
result = jieba.tokenize(u'永和服装饰品有限公司',mode='search')
for tk in result:
print("word %s\t\t start: %d \t\t end:%d" % (tk[0],tk[1],tk[2]))
word 永和 start: 0 end:2
word 服装 start: 2 end:4
word 饰品 start: 4 end:6
word 有限 start: 6 end:8
word 公司 start: 8 end:10
word 有限公司 start: 6 end:10
from jieba.analyse import ChineseAnalyzer
Example: https://github.com/fxsjy/jieba/blob/master/test/test_whoosh.py
$> python -m jieba --help
Jieba command line interface.
positional arguments:
filename input file
optional arguments:
-h, --help show this help message and exit
-d [DELIM], --delimiter [DELIM]
use DELIM instead of ' / ' for word delimiter; or a
space if it is used without DELIM
-p [DELIM], --pos [DELIM]
enable POS tagging; if DELIM is specified, use DELIM
instead of '_' for POS delimiter
-D DICT, --dict DICT use DICT as dictionary
-u USER_DICT, --user-dict USER_DICT
use USER_DICT together with the default dictionary or
DICT (if specified)
-a, --cut-all full pattern cutting (ignored with POS tagging)
-n, --no-hmm don't use the Hidden Markov Model
-q, --quiet don't print loading messages to stderr
-V, --version show program's version number and exit
If no filename specified, use STDIN instead.
By default, Jieba don't build the prefix dictionary unless it's necessary. This takes 1-3 seconds, after which it is not initialized again. If you want to initialize Jieba manually, you can call:
import jieba
jieba.initialize() # (optional)
You can also specify the dictionary (not supported before version 0.28) :
jieba.set_dictionary('data/dict.txt.big')
It is possible to use your own dictionary with Jieba, and there are also two dictionaries ready for download:
A smaller dictionary for a smaller memory footprint: https://github.com/fxsjy/jieba/raw/master/extra_dict/dict.txt.small
There is also a bigger dictionary that has better support for traditional Chinese (繁體):https://github.com/fxsjy/jieba/raw/master/extra_dict/dict.txt.big
By default, an in-between dictionary is used, called dict.txt
and included in the distribution.
In either case, download the file you want, and then call jieba.set_dictionary('data/dict.txt.big')
or just replace the existing dict.txt
.
#-*-coding:utf-8-*-
__author__ = '苏叶'
# ###jieba特性介绍
# 支持三种分词模式:
# 精确模式,试图将句子最精确地切开,适合文本分析;
# 全模式,把句子中所有的可以成词的词语都扫描出来, 速度非常快,但是不能解决歧义;
# 搜索引擎模式,在精确模式的基础上,对长词再次切分,提高召回率,适合用于搜索引擎分词。
# 支持繁体分词。
# 支持自定义词典。
# MIT 授权协议。
# ###分词速度
# 1.5 MB / Second in Full Mode
# 400 KB / Second in Default Mode
# 测试环境: Intel(R) Core(TM) i7-2600 CPU @ 3.4GHz;《围城》.txt
# #一、 第一部分
# ##Part 1. 分词
# jieba.cut的默认参数只有三个,jieba源码如下# cut(self, sentence, cut_all=False, HMM=True)
# jieba.cut的默认参数只有三个,jieba源码如下# cut(self, sentence, cut_all=False, HMM=True)
# 分别为:输入文本 是否为全模式分词 与是否开启HMM进行中文分词(隐马尔科夫模型)
# jieba.cut_for_search 方法接受两个参数:需要分词的字符串;是否使用 HMM 模型。该方法适合用于搜索引擎构建倒排索引的分词,粒度比较细。
# 待分词的字符串可以是 unicode 或 UTF-8 字符串、GBK 字符串。注意:不建议直接输入 GBK 字符串,可能无法预料地错误解码成 UTF-8。
# jieba.cut 以及 jieba.cut_for_search 返回的结构都是一个可迭代的 generator,可以使用 for 循环来获得分词后得到的每一个词语(unicode),或者用
# jieba.lcut 以及 jieba.lcut_for_search 直接返回 list。
# jieba.Tokenizer(dictionary=DEFAULT_DICT) 新建自定义分词器,可用于同时使用不同词典。jieba.dt 为默认分词器,所有全局分词相关函数都是该分词器的映射。
# 1.全模式
import jieba
data1=jieba.cut("我来到山东师范大学",cut_all=True)
print("全模式下:"+"/".join(data1))#全模式下:我/来到/山东/山东师范大学/师范/师范大学/大学
# 2.精确模式(也是默认的模式)
data2=jieba.cut("我来到山东师范大学",cut_all=False)#这玩意默认也是这个,等同于 data2=jieba.cut("我来到山东师范大学")
print("精确模式下:"+"/".join(data2))#精确模式下:我/来到/山东师范大学
# 3.搜索引擎模式
data3=jieba.cut_for_search("我来到山东师范大学")
print("搜索引擎模式下:"+"/".join(data3))#搜索引擎模式下:我/来到/山东/师范/大学/山东师范大学
# ##Part 2. 添加自定义词典
# ###载入词典
# 开发者可以指定自己自定义的词典,以便包含 jieba 词库里没有的词。虽然 jieba 有新词识别能力,但是自行添加新词可以保证更高的正确率。
# 用法: jieba.load_userdict(file_name) # file_name 为自定义词典的路径。
# 词典格式和dict.txt一样,一个词占一行;每一行分三部分,一部分为词语,另一部分为词频(可省略),最后为词性(可省略),用空格隔开。
# 词频可省略,使用计算出的能保证分出该词的词频。
# 更改分词器的 tmp_dir 和 cache_file 属性,可指定缓存文件位置,用于受限的文件系统。
# 举个例子,比如创新办等词语,jieba可以会将其分为创新,办两部分,这个就体现了我们扩展词汇的作用了
# 导入扩展词汇之前
data4=jieba.cut("李小福是创新办主任也是云计算方面的专家")
print("导入扩展词汇之前的分词:"+"/".join(data4))#导入扩展词汇之前的分词:李小福/是/创新/办/主任/也/是/云/计算/方面/的/专家
# 导入扩展词汇之后
jieba.load_userdict("ext_words.txt")#加载扩展词库,里面就两个词汇:创新办、云计算
data5=jieba.cut("李小福是创新办主任也是云计算方面的专家")
print("加载扩展词汇之后:"+"/".join(data5))#加载扩展词汇之后:李小福/是/创新办/主任/也/是/云计算/方面/的/专家
# ###调整词典
# 使用 add_word(word, freq=None, tag=None) 和 del_word(word) 可在程序中动态修改词典。
# 使用 suggest_freq(segment, tune=True) 可调节单个词语的词频,使其能(或不能)被分出来。
# 注意:自动计算的词频在使用 HMM 新词发现功能时可能无效。
print("/".join(jieba.cut("如果放到post中将出错。", HMM = False)))#如果/放到/post/中将/出错/。
#利用调节词频使“中”,“将”都能被分出来
jieba.suggest_freq(("中", "将"), tune = True)
print("/".join(jieba.cut("如果放到post中将出错。", HMM = False)))#如果/放到/post/中/将/出错/。
#动态修改词典
Original = "/".join(jieba.cut("江州市长江大桥参加了长江大桥的通车仪式。", HMM = False))
print( "Original: " + Original)#Original: 江州/市/长江大桥/参加/了/长江大桥/的/通车/仪式/。
# 添加词汇后
jieba.add_word("江大桥", freq = 20000, tag = None)
print("/".join(jieba.cut("江州市长江大桥参加了长江大桥的通车仪式。")))#江州/市长/江大桥/参加/了/长江大桥/的/通车/仪式/。
# ##Part 3. 词性标注
# jieba.posseg.POSTokenizer(tokenizer=None) 新建自定义分词器,tokenizer 参数可指定内部使用的 jieba.Tokenizer 分词器。jieba.posseg.dt 为默认词性标注分词器。
# 标注句子分词后每个词的词性,采用和 ictclas 兼容的标记法。
import jieba.posseg as pseg
words = pseg.cut("我爱北京天安门。")
for w in words:
print("%s %s" %(w.word, w.flag))
#我 r
#爱 v
#北京 ns
#天安门 ns
#。 x
# ##Part 4. 关键词提取
# ###基于 TF-IDF 算法的关键词提取
# import jieba.analyse
# jieba.analyse.extract_tags(sentence, topK = 20, withWeight = False, allowPOS = ())
# sentence:待提取的文本。
# topK:返回几个 TF/IDF 权重最大的关键词,默认值为20。
# withWeight:是否一并返回关键词权重值,默认值为False。
# allowPOS:仅包括指定词性的词,默认值为空,即不进行筛选。
# jieba.analyse.TFIDF(idf_path=None) 新建 TFIDF 实例,idf_path 为 IDF 频率文件。
# optparse模块OptionParser学习
# optparse是专门在命令行添加选项的一个模块。
from optparse import OptionParser
MSG_USAGE = "myprog[ -f ][-s ] arg1[,arg2..]"
optParser = OptionParser(MSG_USAGE)
#以上,产生一个OptionParser的物件optParser。传入的值MSG_USAGE可被调用打印命令时显示出来。
optParser.add_option("-f","--file",action = "store",type="string",dest = "fileName")
optParser.add_option("-v","--vison", action="store_false", dest="verbose",default='gggggg',
help="make lots of noise [default]")
#调用OptionParser.add_option()添加选项,add_option()参数说明:
#action:存储方式,分为三种store, store_false, store_true
#type:类型
#dest:存储的变量
#default:默认值
#help:帮助信息
fakeArgs = ['-f','file.txt','-v','good luck to you', 'arg2', 'arge']
options, args = optParser.parse_args(fakeArgs)
print (options.fileName)
print (options.verbose)
print (options)
print (args)
#调用OptionParser.parse_args()剖析并返回一个directory和一个list
#parse_args()说明:
#如果没有传入参数,parse_args会默认将sys.argv[1:]的值作为默认参数。这里我们将fakeArgs模拟输入的值。
#从返回结果中可以看到,
#options为是一个directory,它的内容fakeArgs为“参数/值 ”的键值对。
#args 是一个list,它的内容是fakeargs除去options后,剩余的输入内容。
#options.version和options.fileName都取到与options中的directory的值。
print (optParser.print_help())
#输出帮助信息
#optParser.print_help()说明:
#1、最开始的的MSG_USAGE的值:在这个地方显示出来了。
#2、自动添加了-h这个参数。
# In[14]:
import jieba.analyse as anl
f = open("C:\\Users\\Luo Chen\\Desktop\\demo.txt", "r").read()
seg = anl.extract_tags(f, topK = 20, withWeight = True)
for tag, weight in seg:
print ("%s %s" %(tag, weight))
# 关键词提取所使用逆向文件频率(IDF)文本语料库可以切换成自定义语料库的路径。
# jieba.analyse.set_idf_path(file_name) #file_name为自定义语料库的路径
# 如:jieba.analyse.set_idf_path("../extra_dict/idf.txt.big")
# .big文件一般是游戏中的文件,比较常见的用途是装载游戏的音乐、声音等文件。
#
# 关键词提取所使用停用词(Stop Words)文本语料库可以切换成自定义语料库的路径。
# jieba.analyse.set_stop_words(file_name) #file_name为自定义语料库的路径。
# 如:jieba.analyse.set_stop_words("../extra_dict/stop_words.txt")
# ###基于 TextRank 算法的关键词提取
# 基本思想:
# 将待抽取关键词的文本进行分词;
# 以固定窗口大小(默认为5,通过span属性调整),词之间的共现关系,构建图;
# 计算图中节点的PageRank,注意是无向带权图。
# jieba.analyse.textrank(sentence, topK = 20, withWeight = False, allowPOS = ('ns', 'n', 'v', 'nv')) 注意默认过滤词性。
# jieba.analyse.TextRank() 新建自定义TextRank实例。
# In[16]:
s = "此外,公司拟对全资子公司吉林欧亚置业有限公司增资4.3亿元,增资后,吉林欧亚置业注册资本由7000万元增加到5亿元。吉林欧亚置业主要经营范围为房地产开发及百货零售等业务。目前在建吉林欧亚城市商业综合体项目。2013年,实现营业收入0万元,实现净利润-139.13万元。"
for x, w in jieba.analyse.textrank(s, topK = 5, withWeight = True):
print("%s %s" % (x, w))
# ##Part 5. 并行分词(多进程分词)
# 原理:将目标文本按行分隔后,把各行文本分配到多个 Python 进程并行分词,然后归并结果,从而获得分词速度的可观提升。
# 基于 python 自带的 multiprocessing 模块,目前暂不支持 Windows。
# 用法:
# jieba.enable_parallel(4) # 开启并行分词模式,参数为并行进程数
# jieba.disable_parallel() # 关闭并行分词模式
# 实验结果:在 4 核 3.4GHz Linux 机器上,对金庸全集进行精确分词,获得了 1MB/s 的速度,是单进程版的 3.3 倍。
# 注意:并行分词仅支持默认分词器 jieba.dt 和 jieba.posseg.dt。
# ##Part 6. Tokenize: 返回词语在原文的起止位置
# 注意:输入参数只接受 unicode
# 两种模式:默认模式、搜索模式。
# ###默认模式
# In[19]:
result = jieba.tokenize(u"永和服装饰品有限公司")
for tk in result:
print("%s \t start at: %d \t end at: %d" %(tk[0], tk[1], tk[2]))
# ###搜索模式
# 把句子中所有的可以成词的词语都扫描出来并确定位置。
# In[20]:
result = jieba.tokenize(u"永和服装饰品有限公司", mode = "search")
for tk in result:
print("%s \t start at: %d \t end at: %d" % (tk[0], tk[1], tk[2]))
# ##Part 7. 延迟加载机制
# jieba 采用延迟加载,import jieba 和 jieba.Tokenizer() 不会立即触发词典的加载,一旦有必要才开始加载词典构建前缀字典。如果你想手工初始 jieba,也可以手动初始化。
# import jieba
# jieba.initialize() #手动初始化(可选)
# 在 0.28 之前的版本是不能指定主词典的路径的,有了延迟加载机制后,你可以改变主词典的路径:
# jieba.set_dictionary("data/dict.txt.big")
# 也可以下载你所需要的词典,然后覆盖jieba/dict.txt即可。
# #二、 第二部分
# ##Part 1. 词频统计、降序排序
# In[21]:
article = open("C:\\Users\\Luo Chen\\Desktop\\demo_long.txt", "r").read()
words = jieba.cut(article, cut_all = False)
word_freq = {}
for word in words:
if word in word_freq:
word_freq[word] += 1
else:
word_freq[word] = 1
freq_word = []
for word, freq in word_freq.items():
freq_word.append((word, freq))
freq_word.sort(key = lambda x: x[1], reverse = True)
max_number = int(input(u"需要前多少位高频词? "))
for word, freq in freq_word[: max_number]:
print (word, freq)
# ##Part 2. 人工去停用词
# 标点符号、虚词、连词不在统计范围内。
# In[22]:
stopwords = []
for word in open("C:\\Users\\Luo Chen\\Desktop\\stop_words.txt", "r"):
stopwords.append(word.strip())
article = open("C:\\Users\\Luo Chen\\Desktop\\demo_long.txt", "r").read()
words = jieba.cut(article, cut_all = False)
stayed_line = ""
for word in words:
if word.encode("utf-8") not in stopwords:
stayed_line += word + " "
print (stayed_line)
# ##Part 3. 合并同义词
# 将同义词列举出来,按下Tab键分隔,把第一个词作为需要显示的词语,后面的词语作为要替代的同义词,一系列同义词放在一行。
# 这里,“北京”、“首都”、“京城”、“北平城”、“故都”为同义词。
# In[24]:
combine_dict = {}
for line in open("C:\\Users\\Luo Chen\\Desktop\\tongyici.txt", "r"):
seperate_word = line.strip().split("\t")
num = len(seperate_word)
for i in range(1, num):
combine_dict[seperate_word[i]] = seperate_word[0]
jieba.suggest_freq("北平城", tune = True)
seg_list = jieba.cut("北京是中国的首都,京城的景色非常优美,就像当年的北平城,我爱这故都的一草一木。", cut_all = False)
f = ",".join(seg_list)
result = open("C:\\Users\\Luo Chen\\Desktop\\output.txt", "w")
result.write(f.encode("utf-8"))
result.close()
for line in open("C:\\Users\\Luo Chen\\Desktop\\output.txt", "r"):
line_1 = line.split(",")
final_sentence = ""
for word in line_1:
if word in combine_dict:
word = combine_dict[word]
final_sentence += word
else:
final_sentence += word
print (final_sentence)
# ##Part 4. 词语提及率
# 主要步骤:分词——过滤停用词(略)——替代同义词——计算词语在文本中出现的概率。
# In[31]:
origin = open("C:\\Users\\Luo Chen\\Desktop\\tijilv.txt", "r").read()
jieba.suggest_freq("晨妈妈", tune = True)
jieba.suggest_freq("大黑牛", tune = True)
jieba.suggest_freq("能力者", tune = True)
seg_list = jieba.cut(origin, cut_all = False)
f = ",".join(seg_list)
output_1 = open("C:\\Users\\Luo Chen\\Desktop\\output_1.txt", "w")
output_1.write(f.encode("utf-8"))
output_1.close()
combine_dict = {}
for w in open("C:\\Users\\Luo Chen\\Desktop\\tongyici.txt", "r"):
w_1 = w.strip().split("\t")
num = len(w_1)
for i in range(0, num):
combine_dict[w_1[i]] = w_1[0]
seg_list_2 = ""
for i in open("C:\\Users\\Luo Chen\\Desktop\\output_1.txt", "r"):
i_1 = i.split(",")
for word in i_1:
if word in combine_dict:
word = combine_dict[word]
seg_list_2 += word
else:
seg_list_2 += word
print (seg_list_2)
# In[35]:
freq_word = {}
seg_list_3 = jieba.cut(seg_list_2, cut_all = False)
for word in seg_list_3:
if word in freq_word:
freq_word[word] += 1
else:
freq_word[word] = 1
freq_word_1 = []
for word, freq in freq_word.items():
freq_word_1.append((word, freq))
freq_word_1.sort(key = lambda x: x[1], reverse = True)
for word, freq in freq_word_1:
print( word, freq)
total_freq = 0
for i in freq_word_1:
total_freq += i[1]
for word, freq in freq_word.items():
freq = float(freq) / float(total_freq)
print( word, freq)
# ##Part 5. 按词性提取
# In[36]:
import jieba.posseg as pseg
word = pseg.cut("李晨好帅,又能力超强,是“大黑牛”,也是一个能力者,还是队里贴心的晨妈妈。")
for w in word:
if w.flag in ["n", "v", "x"]:
print (w.word, w.flag)