举例说明如何用IKAnalyzer实现在android应用程序上面的中文分词

我用的jar包及其版本为:IKAnalyzer2012_u6.jar、lucene-analyzers-3.6.1.jar、lucene-highlighter-3.6.1.jar、lucene-core-3.6.1.jar。这些jar包我都上传到我的资源里面了,有需要的朋友可以到我的资源里面去下载,当然,也可以去官方下载。

 

代码如下:

Participle.java如下:

 

package com.my.participle;

import java.io.IOException;
import java.io.StringReader;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.wltea.analyzer.lucene.IKAnalyzer;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Participle extends Activity {
 
 private TextView tv01;
 private TextView tv02;
 private static final String s="徐怀钰是中国台湾著名流行女歌手、演员、华语乐坛平民天后";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv01=(TextView)findViewById(R.id.tv01);
        tv02=(TextView)findViewById(R.id.tv02);
        tv01.setText(s);
       
        tv02.setText(this.participle(s));
    }
   
    public String participle(String s){
     StringBuilder sb=new StringBuilder();
     String str="";
     Analyzer analyzer=new IKAnalyzer(true);
        StringReader reader=new StringReader(s);
        TokenStream ts=analyzer.tokenStream("", reader);
        CharTermAttribute term=ts.getAttribute(CharTermAttribute.class);
        try {
   while(ts.incrementToken()){
    System.out.print(term.toString()+"|"); 
    sb.append(term.toString()+"|");
   }
   str=sb.toString();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
        return str;
    }
}

 

 

main.xml如下:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
    <TextView
        android:id="@+id/tv02"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</LinearLayout>

 

 

下面说明一个问题:在Eclipse中,一个纯Java文件与一个Android项目实现中文分词的区别之处。

在Eclipse中写一个纯java文件时,那些jar包需要通过Build Path-->Configure  Build  Path-->Libraries-->Add  External JARS来直接导入这些jar包,它的项目配置图如下所示:

 

而在Eclipse中,一个Android项目实现中文分词时,需要新建一个文件夹(这个文件夹一般以libs来命名),然后把这些jar包及一些配置文件放入这个文件夹中,其项目配置图如下所示:

 

 

注意:

如果在Android项目中按照一个纯Java项目的方法来导入这些Jar包的话,会出现这样的错误:

java.lang.NoClassDefFoundError: org.wltea.analyzer.lucene.IKAnalyzer


 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章