利用ik分词并返回分词后的结果

使用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;
	}
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值