有三点要注意(要不然扩展词典始终不生效):
package com.org; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import org.wltea.analyzer.core.IKSegmenter; import org.wltea.analyzer.core.Lexeme; public class IKAnalyzerTest { public static void main(String[] args) { String str = "最希望从企业得到的是独家的内容或销售信息,获得打折或促销信息等;最不希望企业进行消息或广告轰炸及访问用户的个人信息等。这值得使用社会化媒体的企业研究"; IKAnalysis(str); } public static String IKAnalysis(String str) { StringBuffer sb = new StringBuffer(); try { // InputStream in = new FileInputStream(str);// byte[] bt = str.getBytes();// str InputStream ip = new ByteArrayInputStream(bt); Reader read = new InputStreamReader(ip); IKSegmenter iks = new IKSegmenter(read, true); Lexeme t; while ((t = iks.next()) != null) { sb.append(t.getLexemeText() + " , "); } sb.delete(sb.length() - 1, sb.length()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(sb.toString()); return sb.toString(); } }
附加:手动添加相关词库
public static void main(String[] args) throws IOException {
String s = "中文分词工具包";
Configuration cfg = DefualtConfig.getInstance(); //加载词库
cfg.setUseSmart(true); //设置智能分词
Dictionary.initial(cfg);
Dictionary dictionary = Dictionary.getSingleton();
// List<String> words = new ArrayList<String>();
// words.add("基础班");
// words.add("高级会计实务");
// dictionary.addWords(words); //自动添加自定义词
System.out.println(cfg.getMainDictionary()); // 系统默认词库
System.out.println(cfg.getQuantifierDicionary());
Hit hit = dictionary.matchInMainDict("基础班".toCharArray());
System.out.println(hit.isMatch());
System.out.println(queryWords(s));
}
/**
* IK 分词
*
* @param query
* @return
* @throws IOException
*/
public static List<String> queryWords(String query) throws IOException {
List<String> list = new ArrayList<String>();
StringReader input = new StringReader(query.trim());
IKSegmenter ikSeg = new IKSegmenter(input, true);// true 用智能分词 ,false细粒度
for (Lexeme lexeme = ikSeg.next(); lexeme != null; lexeme = ikSeg.next()) {
list.add(lexeme.getLexemeText());
}
return list;
}