jieba分詞制妄,學(xué)習(xí),為了全面了解該模塊泵三,耕捞,預(yù)設(shè)學(xué)習(xí)路線:官方文檔——優(yōu)秀博客文章——實(shí)踐學(xué)習(xí)
-
官方文檔部分
(文檔鏈接)
jieba
“結(jié)巴”中文分詞:做最好的 Python 中文分詞組件
"Jieba" (Chinese for "to stutter") Chinese text segmentation: built to be the best Python Chinese word segmentation module.
- Scroll down for English documentation.
特點(diǎn)
-
支持三種分詞模式:
- 精確模式,試圖將句子最精確地切開(kāi)烫幕,適合文本分析俺抽;
- 全模式,把句子中所有的可以成詞的詞語(yǔ)都掃描出來(lái), 速度非辰下快磷斧,但是不能解決歧義;
- 搜索引擎模式,在精確模式的基礎(chǔ)上弛饭,對(duì)長(zhǎng)詞再次切分冕末,提高召回率,適合用于搜索引擎分詞孩哑。
支持繁體分詞
支持自定義詞典
MIT 授權(quán)協(xié)議
安裝說(shuō)明
代碼對(duì) Python 2/3 均兼容
- 全自動(dòng)安裝:
easy_install jieba
或者pip install jieba
/pip3 install jieba
- 半自動(dòng)安裝:先下載 http://pypi.python.org/pypi/jieba/ 栓霜,解壓后運(yùn)行
python setup.py install
- 手動(dòng)安裝:將 jieba 目錄放置于當(dāng)前目錄或者 site-packages 目錄
- 通過(guò)
import jieba
來(lái)引用
算法
- 基于前綴詞典實(shí)現(xiàn)高效的詞圖掃描翠桦,生成句子中漢字所有可能成詞情況所構(gòu)成的有向無(wú)環(huán)圖 (DAG)
- 采用了動(dòng)態(tài)規(guī)劃查找最大概率路徑, 找出基于詞頻的最大切分組合
- 對(duì)于未登錄詞横蜒,采用了基于漢字成詞能力的 HMM 模型,使用了 Viterbi 算法
主要功能
- 分詞
-
jieba.cut
方法接受三個(gè)輸入?yún)?shù): 需要分詞的字符串销凑;cut_all 參數(shù)用來(lái)控制是否采用全模式丛晌;HMM 參數(shù)用來(lái)控制是否使用 HMM 模型 -
jieba.cut_for_search
方法接受兩個(gè)參數(shù):需要分詞的字符串;是否使用 HMM 模型斗幼。該方法適合用于搜索引擎構(gòu)建倒排索引的分詞澎蛛,粒度比較細(xì) - 待分詞的字符串可以是 unicode 或 UTF-8 字符串、GBK 字符串蜕窿。注意:不建議直接輸入 GBK 字符串谋逻,可能無(wú)法預(yù)料地錯(cuò)誤解碼成 UTF-8
-
jieba.cut
以及jieba.cut_for_search
返回的結(jié)構(gòu)都是一個(gè)可迭代的 generator,可以使用 for 循環(huán)來(lái)獲得分詞后得到的每一個(gè)詞語(yǔ)(unicode)桐经,或者用 -
jieba.lcut
以及jieba.lcut_for_search
直接返回 list -
jieba.Tokenizer(dictionary=DEFAULT_DICT)
新建自定義分詞器毁兆,可用于同時(shí)使用不同詞典。jieba.dt
為默認(rèn)分詞器阴挣,所有全局分詞相關(guān)函數(shù)都是該分詞器的映射气堕。
代碼示例
# encoding=utf-8
import jieba
seg_list = jieba.cut("我來(lái)到北京清華大學(xué)", cut_all=True)
print("Full Mode: " + "/ ".join(seg_list)) # 全模式
seg_list = jieba.cut("我來(lái)到北京清華大學(xué)", cut_all=False)
print("Default Mode: " + "/ ".join(seg_list)) # 精確模式
seg_list = jieba.cut("他來(lái)到了網(wǎng)易杭研大廈") # 默認(rèn)是精確模式
print(", ".join(seg_list))
seg_list = jieba.cut_for_search("小明碩士畢業(yè)于中國(guó)科學(xué)院計(jì)算所,后在日本京都大學(xué)深造") # 搜索引擎模式
print(", ".join(seg_list))
輸出:
【全模式】: 我/ 來(lái)到/ 北京/ 清華/ 清華大學(xué)/ 華大/ 大學(xué)
【精確模式】: 我/ 來(lái)到/ 北京/ 清華大學(xué)
【新詞識(shí)別】:他, 來(lái)到, 了, 網(wǎng)易, 杭研, 大廈 (此處畔咧,“杭研”并沒(méi)有在詞典中茎芭,但是也被Viterbi算法識(shí)別出來(lái)了)
【搜索引擎模式】: 小明, 碩士, 畢業(yè), 于, 中國(guó), 科學(xué), 學(xué)院, 科學(xué)院, 中國(guó)科學(xué)院, 計(jì)算, 計(jì)算所, 后, 在, 日本, 京都, 大學(xué), 日本京都大學(xué), 深造
- 添加自定義詞典
載入詞典
- 開(kāi)發(fā)者可以指定自己自定義的詞典,以便包含 jieba 詞庫(kù)里沒(méi)有的詞誓沸。雖然 jieba 有新詞識(shí)別能力梅桩,但是自行添加新詞可以保證更高的正確率
- 用法: jieba.load_userdict(file_name) # file_name 為文件類對(duì)象或自定義詞典的路徑
- 詞典格式和
dict.txt
一樣,一個(gè)詞占一行拜隧;每一行分三部分:詞語(yǔ)宿百、詞頻(可省略)、詞性(可省略)虹蓄,用空格隔開(kāi)犀呼,順序不可顛倒。file_name
若為路徑或二進(jìn)制方式打開(kāi)的文件薇组,則文件必須為 UTF-8 編碼外臂。 - 詞頻省略時(shí)使用自動(dòng)計(jì)算的能保證分出該詞的詞頻。
例如:
創(chuàng)新辦 3 i
云計(jì)算 5
凱特琳 nz
臺(tái)中
更改分詞器(默認(rèn)為
jieba.dt
)的tmp_dir
和cache_file
屬性律胀,可分別指定緩存文件所在的文件夾及其文件名宋光,用于受限的文件系統(tǒng)貌矿。-
范例:
自定義詞典:https://github.com/fxsjy/jieba/blob/master/test/userdict.txt
-
用法示例:https://github.com/fxsjy/jieba/blob/master/test/test_userdict.py
之前: 李小福 / 是 / 創(chuàng)新 / 辦 / 主任 / 也 / 是 / 云 / 計(jì)算 / 方面 / 的 / 專家 /
加載自定義詞庫(kù)后: 李小福 / 是 / 創(chuàng)新辦 / 主任 / 也 / 是 / 云計(jì)算 / 方面 / 的 / 專家 /
調(diào)整詞典
使用
add_word(word, freq=None, tag=None)
和del_word(word)
可在程序中動(dòng)態(tài)修改詞典。使用
suggest_freq(segment, tune=True)
可調(diào)節(jié)單個(gè)詞語(yǔ)的詞頻罪佳,使其能(或不能)被分出來(lái)逛漫。注意:自動(dòng)計(jì)算的詞頻在使用 HMM 新詞發(fā)現(xiàn)功能時(shí)可能無(wú)效。
代碼示例:
>>> print('/'.join(jieba.cut('如果放到post中將出錯(cuò)赘艳。', HMM=False)))
如果/放到/post/中將/出錯(cuò)/酌毡。
>>> jieba.suggest_freq(('中', '將'), True)
494
>>> print('/'.join(jieba.cut('如果放到post中將出錯(cuò)。', HMM=False)))
如果/放到/post/中/將/出錯(cuò)/蕾管。
>>> print('/'.join(jieba.cut('「臺(tái)中」正確應(yīng)該不會(huì)被切開(kāi)', HMM=False)))
「/臺(tái)/中/」/正確/應(yīng)該/不會(huì)/被/切開(kāi)
>>> jieba.suggest_freq('臺(tái)中', True)
69
>>> print('/'.join(jieba.cut('「臺(tái)中」正確應(yīng)該不會(huì)被切開(kāi)', HMM=False)))
「/臺(tái)中/」/正確/應(yīng)該/不會(huì)/被/切開(kāi)
- "通過(guò)用戶自定義詞典來(lái)增強(qiáng)歧義糾錯(cuò)能力" --- https://github.com/fxsjy/jieba/issues/14
- 關(guān)鍵詞提取
基于 TF-IDF 算法的關(guān)鍵詞抽取
import jieba.analyse
- jieba.analyse.extract_tags(sentence, topK=20, withWeight=False, allowPOS=())
- sentence 為待提取的文本
- topK 為返回幾個(gè) TF/IDF 權(quán)重最大的關(guān)鍵詞枷踏,默認(rèn)值為 20
- withWeight 為是否一并返回關(guān)鍵詞權(quán)重值,默認(rèn)值為 False
- allowPOS 僅包括指定詞性的詞掰曾,默認(rèn)值為空旭蠕,即不篩選
- jieba.analyse.TFIDF(idf_path=None) 新建 TFIDF 實(shí)例,idf_path 為 IDF 頻率文件
代碼示例 (關(guān)鍵詞提瓤跆埂)
https://github.com/fxsjy/jieba/blob/master/test/extract_tags.py
關(guān)鍵詞提取所使用逆向文件頻率(IDF)文本語(yǔ)料庫(kù)可以切換成自定義語(yǔ)料庫(kù)的路徑
- 用法: jieba.analyse.set_idf_path(file_name) # file_name為自定義語(yǔ)料庫(kù)的路徑
- 自定義語(yǔ)料庫(kù)示例:https://github.com/fxsjy/jieba/blob/master/extra_dict/idf.txt.big
- 用法示例:https://github.com/fxsjy/jieba/blob/master/test/extract_tags_idfpath.py
關(guān)鍵詞提取所使用停止詞(Stop Words)文本語(yǔ)料庫(kù)可以切換成自定義語(yǔ)料庫(kù)的路徑
- 用法: jieba.analyse.set_stop_words(file_name) # file_name為自定義語(yǔ)料庫(kù)的路徑
- 自定義語(yǔ)料庫(kù)示例:https://github.com/fxsjy/jieba/blob/master/extra_dict/stop_words.txt
- 用法示例:https://github.com/fxsjy/jieba/blob/master/test/extract_tags_stop_words.py
關(guān)鍵詞一并返回關(guān)鍵詞權(quán)重值示例
基于 TextRank 算法的關(guān)鍵詞抽取
- jieba.analyse.textrank(sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v')) 直接使用掏熬,接口相同,注意默認(rèn)過(guò)濾詞性秒梅。
- jieba.analyse.TextRank() 新建自定義 TextRank 實(shí)例
算法論文: TextRank: Bringing Order into Texts
基本思想:
- 將待抽取關(guān)鍵詞的文本進(jìn)行分詞
- 以固定窗口大小(默認(rèn)為5旗芬,通過(guò)span屬性調(diào)整),詞之間的共現(xiàn)關(guān)系番电,構(gòu)建圖
- 計(jì)算圖中節(jié)點(diǎn)的PageRank岗屏,注意是無(wú)向帶權(quán)圖
使用示例:
見(jiàn) test/demo.py
- 詞性標(biāo)注
-
jieba.posseg.POSTokenizer(tokenizer=None)
新建自定義分詞器,tokenizer
參數(shù)可指定內(nèi)部使用的jieba.Tokenizer
分詞器漱办。jieba.posseg.dt
為默認(rèn)詞性標(biāo)注分詞器这刷。 - 標(biāo)注句子分詞后每個(gè)詞的詞性,采用和 ictclas 兼容的標(biāo)記法娩井。
- 用法示例
>>> import jieba.posseg as pseg
>>> words = pseg.cut("我愛(ài)北京天安門")
>>> for word, flag in words:
... print('%s %s' % (word, flag))
...
我 r
愛(ài) v
北京 ns
天安門 ns
- 并行分詞
原理:將目標(biāo)文本按行分隔后暇屋,把各行文本分配到多個(gè) Python 進(jìn)程并行分詞,然后歸并結(jié)果洞辣,從而獲得分詞速度的可觀提升
基于 python 自帶的 multiprocessing 模塊咐刨,目前暫不支持 Windows
-
用法:
-
jieba.enable_parallel(4)
# 開(kāi)啟并行分詞模式,參數(shù)為并行進(jìn)程數(shù) -
jieba.disable_parallel()
# 關(guān)閉并行分詞模式
-
例子:https://github.com/fxsjy/jieba/blob/master/test/parallel/test_file.py
實(shí)驗(yàn)結(jié)果:在 4 核 3.4GHz Linux 機(jī)器上扬霜,對(duì)金庸全集進(jìn)行精確分詞定鸟,獲得了 1MB/s 的速度,是單進(jìn)程版的 3.3 倍著瓶。
注意:并行分詞僅支持默認(rèn)分詞器
jieba.dt
和jieba.posseg.dt
联予。
- Tokenize:返回詞語(yǔ)在原文的起止位置
- 注意,輸入?yún)?shù)只接受 unicode
- 默認(rèn)模式
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
- ChineseAnalyzer for Whoosh 搜索引擎
- 引用:
from jieba.analyse import ChineseAnalyzer
- 用法示例:https://github.com/fxsjy/jieba/blob/master/test/test_whoosh.py
- 命令行分詞
使用示例:python -m jieba news.txt > cut_result.txt
命令行選項(xiàng)(翻譯):
使用: python -m jieba [options] filename
結(jié)巴命令行界面。
固定參數(shù):
filename 輸入文件
可選參數(shù):
-h, --help 顯示此幫助信息并退出
-d [DELIM], --delimiter [DELIM]
使用 DELIM 分隔詞語(yǔ)沸久,而不是用默認(rèn)的' / '季眷。
若不指定 DELIM,則使用一個(gè)空格分隔卷胯。
-p [DELIM], --pos [DELIM]
啟用詞性標(biāo)注子刮;如果指定 DELIM吹艇,詞語(yǔ)和詞性之間
用它分隔篷帅,否則用 _ 分隔
-D DICT, --dict DICT 使用 DICT 代替默認(rèn)詞典
-u USER_DICT, --user-dict USER_DICT
使用 USER_DICT 作為附加詞典,與默認(rèn)詞典或自定義詞典配合使用
-a, --cut-all 全模式分詞(不支持詞性標(biāo)注)
-n, --no-hmm 不使用隱含馬爾可夫模型
-q, --quiet 不輸出載入信息到 STDERR
-V, --version 顯示版本信息并退出
如果沒(méi)有指定文件名泉粉,則使用標(biāo)準(zhǔn)輸入卵慰。
--help
選項(xiàng)輸出:
$> 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.
延遲加載機(jī)制
jieba 采用延遲加載沙郭,import jieba
和 jieba.Tokenizer()
不會(huì)立即觸發(fā)詞典的加載佛呻,一旦有必要才開(kāi)始加載詞典構(gòu)建前綴字典裳朋。如果你想手工初始 jieba,也可以手動(dòng)初始化吓著。
import jieba
jieba.initialize() # 手動(dòng)初始化(可選)
在 0.28 之前的版本是不能指定主詞典的路徑的鲤嫡,有了延遲加載機(jī)制后,你可以改變主詞典的路徑:
jieba.set_dictionary('data/dict.txt.big')
例子: https://github.com/fxsjy/jieba/blob/master/test/test_change_dictpath.py
其他詞典
占用內(nèi)存較小的詞典文件 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')
其他語(yǔ)言實(shí)現(xiàn)
結(jié)巴分詞 Java 版本
作者:piaolingxue 地址:https://github.com/huaban/jieba-analysis
結(jié)巴分詞 C++ 版本
作者:yanyiwu 地址:https://github.com/yanyiwu/cppjieba
結(jié)巴分詞 Node.js 版本
作者:yanyiwu 地址:https://github.com/yanyiwu/nodejieba
結(jié)巴分詞 Erlang 版本
作者:falood 地址:https://github.com/falood/exjieba
結(jié)巴分詞 R 版本
作者:qinwf 地址:https://github.com/qinwf/jiebaR
結(jié)巴分詞 iOS 版本
作者:yanyiwu 地址:https://github.com/yanyiwu/iosjieba
結(jié)巴分詞 PHP 版本
作者:fukuball 地址:https://github.com/fukuball/jieba-php
結(jié)巴分詞 .NET(C#) 版本
作者:anderscui 地址:https://github.com/anderscui/jieba.NET/
結(jié)巴分詞 Go 版本
- 作者: wangbin 地址: https://github.com/wangbin/jiebago
- 作者: yanyiwu 地址: https://github.com/yanyiwu/gojieba
系統(tǒng)集成
分詞速度
- 1.5 MB / Second in Full Mode
- 400 KB / Second in Default Mode
- 測(cè)試環(huán)境: Intel(R) Core(TM) i7-2600 CPU @ 3.4GHz;《圍城》.txt
常見(jiàn)問(wèn)題
1. 模型的數(shù)據(jù)是如何生成的纺裁?
詳見(jiàn): https://github.com/fxsjy/jieba/issues/7
2. “臺(tái)中”總是被切成“臺(tái) 中”诫肠?(以及類似情況)
P(臺(tái)中) < P(臺(tái))×P(中),“臺(tái)中”詞頻不夠?qū)е缕涑稍~概率較低
解決方法:強(qiáng)制調(diào)高詞頻
jieba.add_word('臺(tái)中')
或者 jieba.suggest_freq('臺(tái)中', True)
3. “今天天氣 不錯(cuò)”應(yīng)該被切成“今天 天氣 不錯(cuò)”欺缘?(以及類似情況)
解決方法:強(qiáng)制調(diào)低詞頻
jieba.suggest_freq(('今天', '天氣'), True)
或者直接刪除該詞 jieba.del_word('今天天氣')
4. 切出了詞典中沒(méi)有的詞語(yǔ)栋豫,效果不理想?
解決方法:關(guān)閉新詞發(fā)現(xiàn)
jieba.cut('豐田太省了', HMM=False)
jieba.cut('我們中出了一個(gè)叛徒', HMM=False)
更多問(wèn)題請(qǐng)點(diǎn)擊:https://github.com/fxsjy/jieba/issues?sort=updated&state=closed
修訂歷史
https://github.com/fxsjy/jieba/blob/master/Changelog
jieba
"Jieba" (Chinese for "to stutter") Chinese text segmentation: built to be the best Python Chinese word segmentation module.
Features
- Support three types of segmentation mode:
- Accurate Mode attempts to cut the sentence into the most accurate segmentations, which is suitable for text analysis.
- Full Mode gets all the possible words from the sentence. Fast but not accurate.
- 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.
- Supports Traditional Chinese
- Supports customized dictionaries
- MIT License
Online demo
http://jiebademo.ap01.aws.af.cm/
(Powered by Appfog)
Usage
- Fully automatic installation:
easy_install jieba
orpip install jieba
- Semi-automatic installation: Download http://pypi.python.org/pypi/jieba/ , run
python setup.py install
after extracting. - Manual installation: place the
jieba
directory in the current directory or pythonsite-packages
directory. -
import jieba
.
Algorithm
- Based on a prefix dictionary structure to achieve efficient word graph scanning. Build a directed acyclic graph (DAG) for all possible word combinations.
- Use dynamic programming to find the most probable combination based on the word frequency.
- For unknown words, a HMM-based model is used with the Viterbi algorithm.
Main Functions
- Cut
- The
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. - The input string can be an unicode/str object, or a str/bytes object which is encoded in UTF-8 or GBK. Note that using GBK encoding is not recommended because it may be unexpectly decoded as UTF-8.
-
jieba.cut
andjieba.cut_for_search
returns an generator, from which you can use afor
loop to get the segmentation result (in unicode). -
jieba.lcut
andjieba.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("我來(lái)到北京清華大學(xué)", cut_all=True)
print("Full Mode: " + "/ ".join(seg_list)) # 全模式
seg_list = jieba.cut("我來(lái)到北京清華大學(xué)", cut_all=False)
print("Default Mode: " + "/ ".join(seg_list)) # 默認(rèn)模式
seg_list = jieba.cut("他來(lái)到了網(wǎng)易杭研大廈")
print(", ".join(seg_list))
seg_list = jieba.cut_for_search("小明碩士畢業(yè)于中國(guó)科學(xué)院計(jì)算所谚殊,后在日本京都大學(xué)深造") # 搜索引擎模式
print(", ".join(seg_list))
Output:
[Full Mode]: 我/ 來(lái)到/ 北京/ 清華/ 清華大學(xué)/ 華大/ 大學(xué)
[Accurate Mode]: 我/ 來(lái)到/ 北京/ 清華大學(xué)
[Unknown Words Recognize] 他, 來(lái)到, 了, 網(wǎng)易, 杭研, 大廈 (In this case, "杭研" is not in the dictionary, but is identified by the Viterbi algorithm)
[Search Engine Mode]: 小明, 碩士, 畢業(yè), 于, 中國(guó), 科學(xué), 學(xué)院, 科學(xué)院, 中國(guó)科學(xué)院, 計(jì)算, 計(jì)算所, 后, 在, 日本, 京都, 大學(xué), 日本京都大學(xué), 深造
- Add a custom dictionary
Load dictionary
- Developers can specify their own custom dictionary to be included in the jieba default dictionary. Jieba is able to identify new words, but you can add your own new words can ensure a higher accuracy.
- Usage:
jieba.load_userdict(file_name)
# file_name is a file-like object or the path of the custom dictionary - The dictionary format is the same as that of
dict.txt
: one word per line; each line is divided into three parts separated by a space: word, word frequency, POS tag. Iffile_name
is a path or a file opened in binary mode, the dictionary must be UTF-8 encoded. - The word frequency and POS tag can be omitted respectively. The word frequency will be filled with a suitable value if omitted.
For example:
創(chuàng)新辦 3 i
云計(jì)算 5
凱特琳 nz
臺(tái)中
Change a Tokenizer's
tmp_dir
andcache_file
to specify the path of the cache file, for using on a restricted file system.-
Example:
云計(jì)算 5 李小福 2 創(chuàng)新辦 3 [Before]: 李小福 / 是 / 創(chuàng)新 / 辦 / 主任 / 也 / 是 / 云 / 計(jì)算 / 方面 / 的 / 專家 / [After]: 李小福 / 是 / 創(chuàng)新辦 / 主任 / 也 / 是 / 云計(jì)算 / 方面 / 的 / 專家 /
Modify dictionary
Use
add_word(word, freq=None, tag=None)
anddel_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中將出錯(cuò)丧鸯。', HMM=False)))
如果/放到/post/中將/出錯(cuò)/。
>>> jieba.suggest_freq(('中', '將'), True)
494
>>> print('/'.join(jieba.cut('如果放到post中將出錯(cuò)嫩絮。', HMM=False)))
如果/放到/post/中/將/出錯(cuò)/丛肢。
>>> print('/'.join(jieba.cut('「臺(tái)中」正確應(yīng)該不會(huì)被切開(kāi)', HMM=False)))
「/臺(tái)/中/」/正確/應(yīng)該/不會(huì)/被/切開(kāi)
>>> jieba.suggest_freq('臺(tái)中', True)
69
>>> print('/'.join(jieba.cut('「臺(tái)中」正確應(yīng)該不會(huì)被切開(kāi)', HMM=False)))
「/臺(tái)中/」/正確/應(yīng)該/不會(huì)/被/切開(kāi)
- Keyword Extraction
import jieba.analyse
-
jieba.analyse.extract_tags(sentence, topK=20, withWeight=False, allowPOS=())
-
sentence
: the text to be extracted -
topK
: return how many keywords with the highest TF/IDF weights. The default value is 20 -
withWeight
: whether return TF/IDF weights with the keywords. The default value is False -
allowPOS
: 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
- Usage:
jieba.analyse.set_idf_path(file_name) # file_name is the path for the custom corpus
- Custom Corpus Sample:https://github.com/fxsjy/jieba/blob/master/extra_dict/idf.txt.big
- Sample Code:https://github.com/fxsjy/jieba/blob/master/test/extract_tags_idfpath.py
Developers can specify their own custom stop words corpus in jieba keyword extraction
- Usage:
jieba.analyse.set_stop_words(file_name) # file_name is the path for the custom corpus
- Custom Corpus Sample:https://github.com/fxsjy/jieba/blob/master/extra_dict/stop_words.txt
- Sample Code:https://github.com/fxsjy/jieba/blob/master/test/extract_tags_stop_words.py
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.
- Part of Speech Tagging
-
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. - Tags the POS of each word after segmentation, using labels compatible with ictclas.
- Example:
>>> import jieba.posseg as pseg
>>> words = pseg.cut("我愛(ài)北京天安門")
>>> for w in words:
... print('%s %s' % (w.word, w.flag))
...
我 r
愛(ài) v
北京 ns
天安門 ns
- Parallel Processing
Principle: Split target text by line, assign the lines into multiple Python processes, and then merge the results, which is considerably faster.
Based on the multiprocessing module of Python.
-
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
andjieba.posseg.dt
.
- Tokenize: return words with position
- The input must be unicode
- Default mode
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
- Search mode
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
- ChineseAnalyzer for Whoosh
from jieba.analyse import ChineseAnalyzer
- Example: https://github.com/fxsjy/jieba/blob/master/test/test_whoosh.py
- Command Line Interface
$> 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.
Initialization
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')
Using Other Dictionaries
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
.
Segmentation speed
- 1.5 MB / Second in Full Mode
- 400 KB / Second in Default Mode
- Test Env: Intel(R) Core(TM) i7-2600 CPU @ 3.4GHz;《圍城》.txt