IKAnalyzer 在项目中的应用及在网上查询的部分实例资料

来源:互联网 发布:android 开发必备软件 编辑:程序博客网 时间:2024/06/05 02:40

IK Analyzer基于lucene实现的分词开源框架,下载路径:http://code.google.com/p/ik-analyzer/downloads/list

需要在项目中引入:

IKAnalyzer.cfg.xml

IKAnalyzer2012.jar

lucene-core-3.6.0.jar

stopword.dic

项目中的应用

private String convertKeyword(String keyWord) throws Exception{if(keyWord == null){return "";}StringBuffer retuString = new StringBuffer();//默认是最细粒度分词,智能切分词传trueIKAnalyzer analyzer = new IKAnalyzer(); TokenStream tokenStream = analyzer.tokenStream("content",new StringReader(keyWord));tokenStream.addAttribute(TermAttribute.class);tokenStream.reset(); while (tokenStream.incrementToken()) {TermAttribute charTermAttribute = (TermAttribute) tokenStream.getAttribute(TermAttribute.class);String participle = charTermAttribute.toString().split("=").length > 1 ? charTermAttribute.toString().split("=")[1] : "";retuString.append(participle).append(" ");}tokenStream.end();tokenStream.close();return retuString.toString();}


示例代码如下(使用IK Analyzer): 

[java] view plain copy
  1. package com.haha.test;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.StringReader;  
  5. import org.apache.lucene.analysis.Analyzer;  
  6. import org.apache.lucene.analysis.TokenStream;  
  7. import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;  
  8. import org.wltea.analyzer.lucene.IKAnalyzer;  
  9.   
  10. public class Test2 {  
  11.     public static void main(String[] args) throws IOException {  
  12.         String text="基于java语言开发的轻量级的中文分词工具包";  
  13.         //创建分词对象  
  14.         Analyzer anal=new IKAnalyzer(true);       
  15.         StringReader reader=new StringReader(text);  
  16.         //分词  
  17.         TokenStream ts=anal.tokenStream("", reader);  
  18.         CharTermAttribute term=ts.getAttribute(CharTermAttribute.class);  
  19.         //遍历分词数据  
  20.         while(ts.incrementToken()){  
  21.             System.out.print(term.toString()+"|");  
  22.         }  
  23.         reader.close();  
  24.         System.out.println();  
  25.     }  
  26.   
  27. }  


运行后结果:

基于|Java|语言|开发|的|轻量级|的|中文|分词|工具包|

 

使用(lucene)实现:

[java] view plain copy
  1. package com.haha.test;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.StringReader;  
  5.   
  6. import org.wltea.analyzer.core.IKSegmenter;  
  7. import org.wltea.analyzer.core.Lexeme;  
  8.   
  9. public class Test3 {  
  10.       
  11.     public static void main(String[] args) throws IOException {  
  12.         String text="基于java语言开发的轻量级的中文分词工具包";  
  13.         StringReader sr=new StringReader(text);  
  14.         IKSegmenter ik=new IKSegmenter(sr, true);  
  15.         Lexeme lex=null;  
  16.         while((lex=ik.next())!=null){  
  17.             System.out.print(lex.getLexemeText()+"|");  
  18.         }  
  19.     }  
  20.   
  21. }  
0 0
原创粉丝点击