hanlp是一款開源的中文語言處理工具。
環境:jdk1.7、myeclipse8.5、win64
官網:http://hanlp.linrunsoft.com/
git下載使用說明地址:https://github.com/hankcs/HanLP
在線演示地址:http://hanlp.com/?sentence=http://hanlp.com/
百度雲鏈接: https://pan.baidu.com/s/1kBJH1PAE4-S_Mfn_igp4Vw
使用步驟
1.官網下載本地詞庫
2.下載jar包與配置文件
3.新建工程導入jar,配置文件
4.修改配置文件 root=D:/datacjy/hanlp 爲本地下載好的詞庫
5.開始使用
上面給的百度雲鏈接是本人下載的目前官網最新的1.6.8版本,裏面有詞庫,jar包與配置文件、官網demo工程,本人測試工程
工程解析:
1.com.hankcs包下是官網demo中的 test文件夾下的代碼,工程完善可直接運行
2.hanlp.properties 是配置文件需要修改下載後的本地詞庫位置
3.lib下是jar包,源碼包
配置文件修改:
配置文件的作用是告訴HanLP數據包的位置,只需修改第一行
root=D:/datacjy/hanlp
爲data的父目錄即可,比如data目錄是/Users/hankcs/Documents/data,那麼root=/Users/hankcs/Documents/ 。
測試
package com.hankcs.demo;
import com.hankcs.hanlp.HanLP;
/**
- 第一個Demo,驚鴻一瞥
- @author hankcs
*/
public class DemoAtFirstSight
{
public static void main(String[] args)
{
System.out.println("首次編譯運行時,HanLP會自動構建詞典緩存,請稍候……");
// HanLP.Config.enableDebug(); // 爲了避免你等得無聊,開啓調試模式說點什麼:-)
System.out.println(HanLP.segment("你好,歡迎使用HanLP漢語處理包!接下來請從其他Demo中體驗HanLP豐富的功能~"));
}
}
/*
首次編譯運行時,HanLP會自動構建詞典緩存,請稍候……
[你好/vl, ,/w, 歡迎/v, 使用/v, HanLP/nx, 漢語/gi, 處理/vn, 包/v, !/w, 接下來/vl, 請/v, 從/p, 其他/rzv, Demo/nx, 中/f, 體驗/v, HanLP/nx, 豐富/a, 的/ude1, 功能/n, ~/nx]
/
演示用戶詞典的動態增刪
package com.hankcs.demo;
import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.collection.AhoCorasick.AhoCorasickDoubleArrayTrie;
import com.hankcs.hanlp.dictionary.BaseSearcher;
import com.hankcs.hanlp.dictionary.CoreDictionary;
import com.hankcs.hanlp.dictionary.CustomDictionary;
import java.util.Map;
/**
- 演示用戶詞典的動態增刪
-
@author hankcs
*/
public class DemoCustomDictionary
{
public static void main(String[] args)
{
// 動態增加
CustomDictionary.add("攻城獅");
// 強行插入
CustomDictionary.insert("白富美", "nz 1024");
// 刪除詞語(註釋掉試試)
// CustomDictionary.remove("攻城獅");
System.out.println(CustomDictionary.add("單身狗", "nz 1024 n 1"));
// System.out.println(CustomDictionary.get("單身狗"));String text = "攻城獅逆襲單身狗,迎娶白富美,走上人生巔峯"; // 怎麼可能噗哈哈! // DoubleArrayTrie分詞 final char[] charArray = text.toCharArray(); CustomDictionary.parseText(charArray, new AhoCorasickDoubleArrayTrie.IHit<CoreDictionary.Attribute>() { @Override public void hit(int begin, int end, CoreDictionary.Attribute value) {
// System.out.printf("[%d:%d]=%s %s\n", begin, end, new String(charArray, begin, end - begin), value);
}
});
// 首字哈希之後二分的trie樹分詞
BaseSearcher searcher = CustomDictionary.getSearcher(text);
Map.Entry entry;
while ((entry = searcher.next()) != null)
{
// System.out.println(entry);
}// 標準分詞 System.out.println(HanLP.segment(text)); // Note:動態增刪不會影響詞典文件 // 目前CustomDictionary使用DAT儲存詞典文件中的詞語,用BinTrie儲存動態加入的詞語,前者性能高,後者性能低 // 之所以保留動態增刪功能,一方面是歷史遺留特性,另一方面是調試用;未來可能會去掉動態增刪特性。
}
}
//true
//[攻城獅/nz, 逆襲/nz, 單身狗/nz, ,/w, 迎娶/v, 白富美/nz, ,/w, 走上/v, 人生/n, 巔峯/n]
//自定義詞:攻城獅、單身狗、白富美
注意:修改配置文件本地詞庫位置
文章來源於風zi的博客