本文共 2646 字,大约阅读时间需要 8 分钟。
hanlp是一款开源的中文语言处理工具。
环境:jdk1.7、myeclipse8.5、win64
官网:
git下载使用说明地址:在线演示地址:百度云链接:使用步骤
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;
/**
演示用户词典的动态增删
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(){ @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的博客
转载于:https://blog.51cto.com/13993767/2333343