IK分词器用法

一)新建maven工程

1.1)项目结构如下:

1.2)IKAnalyzer.cfg.xml内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>IK Analyzer 扩展配置</comment>
<entry key="ext_dict">extend.dic;</entry>
<entry key="ext_stopwords">stopword.dic;</entry>
</properties>

1.3)在pom文件中添加如下jar

<dependency>
<groupId>com.janeluo</groupId>
<artifactId>ikanalyzer</artifactId>
<version>2012_u6</version>
</dependency>
<dependency>
<groupId>org.apache.lucene</groupId>
<artifactId>lucene-core</artifactId>
<version>4.7.2</version>
</dependency>

二)新建类IKAnalyzerSupplyProduct
public class IKAnalyzerSupplyProduct {
public static String startIKAnalyzer(String line) throws IOException{
IKAnalyzer analyzer = new IKAnalyzer();
// 使用智能分词
analyzer.setUseSmart(true);
// 打印分词结果
try {
return printAnalysisResult(analyzer, line);
} catch (Exception e) {
e.printStackTrace();
}finally{
if(analyzer!=null){
analyzer.close();
}
}
return null;
}
private static String printAnalysisResult(Analyzer analyzer, String keyWord)
throws Exception {
String resultdata="";
String infoData="";
if(keyWord!=""&&keyWord!=null){
TokenStream tokenStream = analyzer.tokenStream("content",
new StringReader(keyWord));
tokenStream.addAttribute(CharTermAttribute.class);
tokenStream.reset();
while (tokenStream.incrementToken()) {
CharTermAttribute charTermAttribute = tokenStream
.getAttribute(CharTermAttribute.class);
String dest= NumberUtil.checkNumber(charTermAttribute.toString().replace("-",""));
boolean mailres= RegExpUtil.isEmail(charTermAttribute.toString());
boolean hpres=RegExpUtil.isHomepage(charTermAttribute.toString());
boolean num=RegExpUtil.isNum(charTermAttribute.toString().replace("-", "").replace("qq", "").replace("QQ", "").replace("+", ""));
if(dest!="CELLPHONE"&&dest!="FIXEDPHONE"&&mailres==false&&hpres==false&&num==false){
infoData=infoData+" "+charTermAttribute.toString();
}
}
if(infoData!=""&&infoData!=null){
resultdata=resultdata+infoData.trim()+"\r\n";
}else{
resultdata="";
}
}
return resultdata;
}

public static void main(String[] args) {
String word ="8月17日,“雄鹰突击-2018”中国和白俄罗斯特种部队联合训练,在北部战区陆军某综合训练基地完成综合演练并举行结训仪式。北部战区副司令员兼北部战区陆军司令员王印芳、白俄罗斯武装力量总参谋长兼国防部第一副部长别洛科涅夫出席结训仪式。" +
"记者在综合演练现场看到,联合突击营救行动展开后,双方特战队员混编成多个战斗小组,各小组指挥员通过眼神和手语快速交流现场侦察情况,分配任务、搜索前行、交替掩护等一系列动作顺畅默契,判定目标后迅即展开行动。演练中,中白特战队员密切协同,出色完成立体封控、分区搜歼等一系列行动,赢得两军观摩团阵阵掌声。";
String result=null;
try {
result = IKAnalyzerSupplyProduct.startIKAnalyzer(word);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("result"+result);
}
}

 三)运行结果如下:

可在extend.dic 与 stopword.dic 之间进行调整 分词

猜你喜欢

转载自www.cnblogs.com/fishjar/p/9505041.html