pyhanlp是python版封裝的的HanLP,項目地址:https://github.com/hankcs/pyhanlp
經過測試,HanLP比nltk在中文分詞和實體識別方面都更好用。
如何向pyhanlp添加自定義的詞典?以python 2.7.9爲例:
1.安裝pyhanlp:pip install pyhanlp
2.在字典路徑下添加自定義的詞典:CustomDictionary主詞典文本路徑是data/dictionary/custom/CustomDictionary.txt,用戶可以在此增加自己的詞語(不推薦);也可以單獨新建一個文本文件,通過配置文件;CustomDictionaryPath=data/dictionary/custom/CustomDictionary.txt; 我的詞典.txt;來追加詞典(推薦)。
具體絕對路徑可用hanlp --version獲取:
#hanlp --version
jar 1.6.3: /usr/local/lib/python2.7/site-packages/pyhanlp/static/hanlp-1.6.3.jar
data 1.6.2: /usr/local/lib/python2.7/site-packages/pyhanlp/static/data
config : /usr/local/lib/python2.7/site-packages/pyhanlp/static/hanlp.properties
#cat /usr/local/lib/python2.7/site-packages/pyhanlp/static/hanlp.properties | grep "CustomDictionaryPath"
3.建議在該路徑下添加自己的詞典文件例如 我的詞典.txt,並將其加入上面的properties文件裏的CustomDictionaryPath下面。
#cat 我的詞典.txt
codis集羣 nz 1000
今日頭條 nz 1000
第一列爲詞條,第二列爲詞性(默認爲n),第三列爲詞頻
4.然後需要刪除緩存文件,這樣python纔會重新加載新增的文件:
#rm -f CustomDictionary.txt.bin
5.測試新增的詞典:
python -c "from pyhanlp import *;print(HanLP.segment('codis集羣,今日頭條'))"
五月 16, 2018 4:43:14 下午 com.hankcs.hanlp.corpus.io.IOUtil readBytes
警告: 讀取/usr/local/lib/python2.7/site-packages/pyhanlp/static/data/dictionary/custom/CustomDictionary.txt.bin時發生異常java.io.FileNotFoundException: /usr/local/lib/python2.7/site-packages/pyhanlp/static/data/dictionary/custom/CustomDictionary.txt.bin (沒有那個文件或目錄)
報這個錯誤沒有關係,只是個warning,重新加載緩存文件而已。
文章來源於明月三千里68的博客