java實現中文分詞


IK Analyzer是基於lucene實現的分詞開源框架

下載路徑:http://so.csdn.net/so/search/s.do?q=IKAnalyzer2012.jar&t=doc&o=&s=all&l=null

需要在項目中引入:

  IKAnalyzer2012.jar

  lucene-core-3.6.0.jar

實現的兩種方法:

使用(lucene)實現:

 1 import java.io.IOException;
 2 import java.io.StringReader;
 3 import org.wltea.analyzer.core.IKSegmenter;
 4 import org.wltea.analyzer.core.Lexeme;
 5 
 6 public class Fenci1 {
 7     public static void main(String[] args) throws IOException{
 8         String text="你好,我的世界!";  
 9         StringReader sr=new StringReader(text);  
10         IKSegmenter ik=new IKSegmenter(sr, true);  
11         Lexeme lex=null;  
12         while((lex=ik.next())!=null){  
13             System.out.print(lex.getLexemeText()+",");  
14         } 
15     }
16 
17 }

 

使用(IK Analyzer)實現:

 1 import java.io.IOException;
 2 import java.io.StringReader;
 3 import org.apache.lucene.analysis.Analyzer;
 4 import org.apache.lucene.analysis.TokenStream;
 5 import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
 6 import org.wltea.analyzer.lucene.IKAnalyzer;
 7 
 8 public class Fenci {
 9     public static void main(String[] args) throws IOException {
11             String text="你好,我的世界!";  
12             //創建分詞對象  
13             Analyzer anal=new IKAnalyzer(true);       
14             StringReader reader=new StringReader(text);  
15             //分詞  
16             TokenStream ts=anal.tokenStream("", reader);  
17             CharTermAttribute term=ts.getAttribute(CharTermAttribute.class);  
18             //遍歷分詞數據  
19             while(ts.incrementToken()){  
20                 System.out.print(term.toString()+",");  
21             }  
22             reader.close();  
23             System.out.println(); 
24     }
25 
26 }

運行后結果:

你好,我,的,世界,


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM