1. 程式人生 > >pyhanlp使用者自定義詞典新增

pyhanlp使用者自定義詞典新增

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的部落格