Python NLP (1) HanLP load dict

1. Install HanLP Python interface:

假如你有安裝 Java 那就可以依照下列步驟安裝 HanLP,但還是建議採用手動安裝的方式。

$ sudo pip3 install pyhanlp

執行 hanlp,我在我的 ubuntu 要像 pip3 一樣使用 sudo。

$ sudo hanlp

執行看看 hanlp

$ hanlp

出現下面結果代表安裝成功啦。

usage: hanlp [-h] [-v] {segment,parse,serve,update} ...

HanLP: Han Language Processing v1.7.7

positional arguments:
  {segment,parse,serve,update}
                        which task to perform?
    segment             word segmentation
    parse               dependency parsing
    serve               start http server
    update              update jar and data of HanLP

optional arguments:
  -h, --help            show this help message and exit
  -v, --version         show installed versions of HanLP

2. 測試 pyhanlp

接下來讀取字典檔。字典檔是單詞跟詞性頻率的組合,用空白符號分隔。

from pyhanlp import *

def load_dict():
    IOUtil = JClass("com.hankcs.hanlp.corpus.io.IOUtil")
    core_file = HanLP.Config.CoreDictionaryPath
    print("Core file: ", core_file)
    mini_file = core_file.replace(".txt", ".mini.txt")
    print("Mini file: ", mini_file)
    dic = IOUtil.loadDictionary([mini_file])
    return dic

if __name__ == "__main__":
    dic = load_dict()
    print(dic["希望"])

上例中我們把字典檔從 CoreNatureDictionary.txt 換成 CoreNatureDictionary.mini.txt。

執行結果如下,最後一行代表"希望"各詞性的詞頻:

Core file:  /usr/local/lib/python3.7/site-packages/pyhanlp/static/data/dictionary/CoreNatureDictionary.txt
Mini file:  /usr/local/lib/python3.7/site-packages/pyhanlp/static/data/dictionary/CoreNatureDictionary.mini.txt
v 386 n 96 vn 25 nz 1

用下面的指令來驗證看看我們的字典檔,cat 會逐行顯示 grep 會找尋對應字串:

$ cat /usr/local/lib/python3.7/site-packages/pyhanlp/static/data/dictionary/CoreNatureDictionary.mini.txt | grep 希望

執行結果如下:

希望 v 386 n 96 vn 25 nz 1

3. 關於繁體簡體問題:

假如你仔細看會發現 CoreNatureDictionary.mini.txt 裡面是簡體的,所以有時搜尋繁體字會出現錯誤。

例如我們試圖利用上面的字典搜尋"龟鹤延年"和"龜鶴延年":

print(dic["龟鹤延年"])
print(dic["龜鶴延年"])

我們會得到如下果,None 是因為字典不包含"龜鶴延年":

i 1 
None

我們可以轉繁為簡再利用字典查找:

word = HanLP.convertToSimplifiedChinese("龜鶴延年")
print(word)
print(dic[word])

執行結果如下:

龟鹤延年
i 1 

Reference:

1. 自然語言處理入門

留言

熱門文章