您的位置:首页 > 其它

IKAnalyzer使用停用词词典进行分词

2014-09-30 15:59 417 查看
@Test
// 测试分词的效果,以及停用词典是否起作用
public void test() throws IOException {
	String text = "老爹我们都爱您!";
	Configuration configuration = DefaultConfig.getInstance();
	configuration.setUseSmart(true);
	IKSegmenter ik = new IKSegmenter(new StringReader(text), configuration);
	Lexeme lexeme = null;
	while ((lexeme = ik.next()) != null) {
		System.out.println(lexeme.getLexemeText());
	}
}

第二个例子

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;

import javax.imageio.stream.FileImageInputStream;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.wltea.analyzer.core.IKSegmenter;
import org.wltea.analyzer.core.Lexeme;
import org.wltea.analyzer.lucene.IKAnalyzer;

public class TestStopWords {
	public static void main(String[] args) throws IOException {
		String keyWords = "2012年那个欧洲杯四强赛";
		InputStreamReader isr = new InputStreamReader(new FileInputStream(new File("data/stopword.txt")));
		IKSegmenter ikSegmenter = new IKSegmenter(isr, true);
		Lexeme lexeme = null;
		while((lexeme=ikSegmenter.next())!= null){
			System.out.println(lexeme.getLexemeText());
		}
	}
}


程序的运行结果是:

加载扩展停止词典:stopword.dic
加载扩展停止词典:chinese_stopwords.dic
老爹
都爱

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">ext.dic;</entry>如果有多个扩展词典,那么以分号分隔即可,如下面的两个扩展停止词字典 -->
	<!--用户可以在这里配置自己的扩展停止词字典 -->
	<entry key="ext_stopwords">stopword.dic;chinese_stopwords.dic</entry>
</properties>


注意点:

1、停用词词典必须是UTF-8编码;

2、这里很多跟我一样的新手没办法成功的原因就是被无bom的UTF-8格式给折磨的,IK作者自己也这样说了;

3、如果你不知道啥叫无BOM,也不确定自己的文件是不是UTF-8无bom,那么请在第一行使用回车换行,从第二行开始添加停止词;

4、该配置文件以及停用词词典均存放在src目录下面即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: