使用IK做分词之前需要准备jar包。本文使用的方法只需要IKAnalyzer2012_u6和lucene-core-3.6.0两个jar包即可。关于IK以及lucene的版本,最好使用别人已经使用过的或者本文的版本,因为IK和lucene在不同的版本修改了一些东西导致很多版本的两种包不兼容,运行时会报各种错误和异常。
本文使用jar包链接点击这里
IK分词并返回分词结果
首先我们需要将文本读到字符串中
String filepathfrom = System.getProperty("user.dir") + "\\from\\text.txt";//这一行是你文件的位置,不同格式的文件可自行寻找读成string的方法
File newsfile = new File(filepathfrom);
String str = textToString(newsfile);
然后将string传入分词类,进行分词并返回分词结果。
participle ik = new participle();
String result1 = ik.getParticiple(str);
分词类
public class participle {
public static String getParticiple(String str) {
String result = "";
if (str == null) {
return result;
}
try {
Analyzer analyzer = new IKAnalyzer(true);
StringReader reader = new StringReader(str);
TokenStream ts = analyzer.tokenStream("", reader);
CharTermAttribute term = ts.getAttribute(CharTermAttribute.class);
StringBuffer sb = new StringBuffer();
while (ts.incrementToken()) {
sb.append(term.toString() + " ");
}
result = sb.toString();
reader.close();
// System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}