jieba分詞模塊學(xué)習(xí)

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 算法

主要功能

  1. 分詞

  • 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é), 深造

  1. 添加自定義詞典

載入詞典

  • 開(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_dircache_file 屬性律胀,可分別指定緩存文件所在的文件夾及其文件名宋光,用于受限的文件系統(tǒng)貌矿。

  • 范例:

調(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)
  1. 關(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ù)的路徑

關(guān)鍵詞提取所使用停止詞(Stop Words)文本語(yǔ)料庫(kù)可以切換成自定義語(yǔ)料庫(kù)的路徑

關(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

基本思想:

  1. 將待抽取關(guān)鍵詞的文本進(jìn)行分詞
  2. 以固定窗口大小(默認(rèn)為5旗芬,通過(guò)span屬性調(diào)整),詞之間的共現(xiàn)關(guān)系番电,構(gòu)建圖
  3. 計(jì)算圖中節(jié)點(diǎn)的PageRank岗屏,注意是無(wú)向帶權(quán)圖

使用示例:

見(jiàn) test/demo.py

  1. 詞性標(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
  1. 并行分詞

  • 原理:將目標(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.dtjieba.posseg.dt联予。

  1. 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

  1. ChineseAnalyzer for Whoosh 搜索引擎

  1. 命令行分詞

使用示例: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 jiebajieba.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

其他詞典

  1. 占用內(nèi)存較小的詞典文件 https://github.com/fxsjy/jieba/raw/master/extra_dict/dict.txt.small

  2. 支持繁體分詞更好的詞典文件 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 版本

系統(tǒng)集成

  1. Solr: https://github.com/sing1ee/jieba-solr

分詞速度

  • 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:
  1. Accurate Mode attempts to cut the sentence into the most accurate segmentations, which is suitable for text analysis.
  2. Full Mode gets all the possible words from the sentence. Fast but not accurate.
  3. 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 or pip 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 python site-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

  1. Cut

  • The jieba.cut function accepts three input parameters: the first parameter is the string to be cut; the second parameter is cut_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 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("我來(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é), 深造

  1. 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. If file_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 and cache_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) 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中將出錯(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)
  1. 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

Developers can specify their own custom stop words corpus in jieba keyword extraction

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.

  1. 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
  1. 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 and jieba.posseg.dt.

  1. 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

  1. ChineseAnalyzer for Whoosh

  1. 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:

  1. A smaller dictionary for a smaller memory footprint: https://github.com/fxsjy/jieba/raw/master/extra_dict/dict.txt.small

  2. 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
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末剿干,一起剝皮案震驚了整個(gè)濱河市蜂怎,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌置尔,老刑警劉巖杠步,帶你破解...
    沈念sama閱讀 216,470評(píng)論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡篮愉,警方通過(guò)查閱死者的電腦和手機(jī)腐芍,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,393評(píng)論 3 392
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)试躏,“玉大人猪勇,你說(shuō)我怎么就攤上這事〉咴蹋” “怎么了泣刹?”我有些...
    開(kāi)封第一講書(shū)人閱讀 162,577評(píng)論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)犀被。 經(jīng)常有香客問(wèn)我椅您,道長(zhǎng),這世上最難降的妖魔是什么寡键? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,176評(píng)論 1 292
  • 正文 為了忘掉前任掀泳,我火速辦了婚禮,結(jié)果婚禮上西轩,老公的妹妹穿的比我還像新娘员舵。我一直安慰自己,他們只是感情好藕畔,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,189評(píng)論 6 388
  • 文/花漫 我一把揭開(kāi)白布马僻。 她就那樣靜靜地躺著,像睡著了一般注服。 火紅的嫁衣襯著肌膚如雪韭邓。 梳的紋絲不亂的頭發(fā)上,一...
    開(kāi)封第一講書(shū)人閱讀 51,155評(píng)論 1 299
  • 那天溶弟,我揣著相機(jī)與錄音女淑,去河邊找鬼。 笑死可很,一個(gè)胖子當(dāng)著我的面吹牛诗力,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播我抠,決...
    沈念sama閱讀 40,041評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼苇本,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來(lái)了菜拓?” 一聲冷哼從身側(cè)響起瓣窄,我...
    開(kāi)封第一講書(shū)人閱讀 38,903評(píng)論 0 274
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎纳鼎,沒(méi)想到半個(gè)月后俺夕,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體裳凸,經(jīng)...
    沈念sama閱讀 45,319評(píng)論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,539評(píng)論 2 332
  • 正文 我和宋清朗相戀三年劝贸,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了姨谷。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,703評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡映九,死狀恐怖梦湘,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情件甥,我是刑警寧澤捌议,帶...
    沈念sama閱讀 35,417評(píng)論 5 343
  • 正文 年R本政府宣布,位于F島的核電站引有,受9級(jí)特大地震影響瓣颅,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜譬正,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,013評(píng)論 3 325
  • 文/蒙蒙 一宫补、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧导帝,春花似錦守谓、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,664評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)荞雏。三九已至虐秦,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間凤优,已是汗流浹背悦陋。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,818評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留筑辨,地道東北人俺驶。 一個(gè)月前我還...
    沈念sama閱讀 47,711評(píng)論 2 368
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像棍辕,于是被迫代替她去往敵國(guó)和親暮现。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,601評(píng)論 2 353

推薦閱讀更多精彩內(nèi)容