参考:https://blog.csdn.net/chengyuqiang/article/details/102792839
1.效果:
2.实现过程
2.1导入jar
<dependency> <groupId>com.janeluo</groupId> <artifactId>ikanalyzer</artifactId> <version>2012_u6</version> </dependency>
2.2 编写配置文件
2.2.1 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">local.dic;</entry> <!--用户可以在这里配置自己的扩展停止词字典 --> <entry key="ext_stopwords">stop.dic;</entry> </properties>
2.2.2 local.dic
2.2.3 stop.dic
2.3 测试
工具类:
package cn.ma.life.utils; import org.wltea.analyzer.core.IKSegmenter; import org.wltea.analyzer.core.Lexeme; import java.io.IOException; import java.io.StringReader; import java.util.ArrayList; import java.util.List; public class IKAnalyzerUtil { public static List<String> cut(String msg) throws IOException { StringReader sr = new StringReader(msg); IKSegmenter ik = new IKSegmenter(sr, true); Lexeme lex = null; List<String> list = new ArrayList<>(); while ((lex = ik.next()) != null) { list.add(lex.getLexemeText()); } return list; } }
请求:
package cn.ma.life.controller; import cn.ma.life.utils.IKAnalyzerUtil; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; import java.util.List; @RestController public class AnalyzerController { /** * http://localhost:8081/IkAnalyzer?word=老板请给我一把油纸伞 * * @param word * @return */ @RequestMapping("/IkAnalyzer") public String IkAnalyzer(String word) throws IOException { StringBuffer sb = new StringBuffer(); sb.append("分词后的关键字分别是:"); List<String> list = IKAnalyzerUtil.cut(word); for (int i = 0; i < list.size(); i++) { String s = list.get(i); if (i < list.size() - 1) { sb.append(s); sb.append(","); } else { sb.append(s); } } return sb.toString(); } }