一、分词抽象类Segment
package segment;
import java.util.HashSet;
import java.util.Set;
import util.ReadTXT;
/**
* 分词抽象类
* @author Angela
*/
public abstract class Segment {
protected Set<String> stopwords;//停用词
/**
* 构造函数,初始化各个属性
*/
public Segment(){
stopwords=new HashSet<String>();
}
/**
* 构造函数,初始化各个属性,初始化停用词集
* @param stopwordPath 停用词文件路径
*/
public Segment(String stopwordPath){
stopwords=ReadTXT.toSet(stopwordPath);
}
/**
* 对字符串内容进行分词
* @param content 内容
* @return 由空格符作为分隔符的分词结果String
*/
public abstract String segment(String content);
/**
* @return the stopwords
*/
public Set<String> getStopwords() {
return stopwords;
}
/**
* @param stopwords the stopwords to set
*/
public void setStopwords(Set<String> stopwords) {
this.stopwords = stopwords;
}
}
二、英文分词类EnglishSegment
英文分词需要用到词干提取算法PorterAlgorithm,请参考http://blog.youkuaiyun.com/fighting_no1/article/details/50927162。停用词是我自己整理的。
这里使用Java的lucene开源项目中的StandardAnalyzer标准分词器来对英文进行分词,并使用PorterStem词干提取算法进行词干提取。
package segment;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.en.PorterStemFilter;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
/**
* 英文分词类
* @author Angela
*/
public class EnglishSegment extends Segment{
private Analyzer analyzer;//英文分词器
public EnglishSegment(){
super();
analyzer=new StandardAnalyzer();//默认标准分词器
}
public EnglishSegment(String stopwordPath){
super(stopwordPath);//设置停用词
analyzer=new StandardAnalyzer();//默认标准分词器
}
/**
* 英文分词
* step1 英文词法分析,去除数字、连字符、标点符号、特殊字符
* step2 去停用词
* step3 词干提取
* @param content 文本内容
* @retur