java 自动补全 java 搜索自动匹配 java 汉字拼音搜索
一、依赖jar包
<!-- https://mvnrepository.com/artifact/org.ansj/ansj_seg -->
<dependency>
<groupId>org.ansj</groupId>
<artifactId>ansj_seg</artifactId>
<version>5.1.6</version>
</dependency>
二、代码实现
1、SearcuUtils 实现具体搜索功能
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.nlpcn.commons.lang.index.MemoryIndex;
import org.nlpcn.commons.lang.pinyin.Pinyin;
/**
* description: 使用 ansj_seg 实现简单的文字搜索
* @version v1.0
* @author w
* @date 2020年2月29日下午9:00:42
**/
public class SearcuUtils {
// 构造方法私有化
private SearcuUtils INSTANSE = new SearcuUtils ();
/**|
* description: 实现简单文字搜索
* @param key 用于搜索的关键词
* @param wordList 待搜索的词库
* @return List<String>
* @version v1.0
* @author w
* @date 2020年2月29日 下午9:12:54
*/
@SuppressWarnings("unchecked")
public static List<String> search(String key , List<String> wordList){
MemoryIndex<String> memoryIndex = new MemoryIndex<String>();
if (StringUtils.isBlank(key) || CollectionUtils.isEmpty(wordList)) {
return Collections.EMPTY_LIST;
}
for (String word : wordList) {
// 汉字转为完整拼音,如:中国 -- zhongguo
String fullChar = StringUtils.join(Pinyin.pinyin(word), "");
// 汉字转为拼音缩写,如:中国 -- zg
String firstChar = StringUtils.join(Pinyin.firstChar(word), "");
memoryIndex.addItem(word, word, fullChar, firstChar);
}
return memoryIndex.suggest(key);
}
/**
* description: 加载待搜索的词库 --- 临时用
* @param path
* @return List<String>
* @version v1.0
* @author w
* @date 2020年2月29日 下午9:15:51
*/
public static List<String> loadWordList() {
List<String> list = new ArrayList<>();
list.add("中国");
list.add("中华人民共和国");
list.add("中国人民");
list.add("我爱中国");
return list;
}
}
2、SearchController 搜索匹配 Controller
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.runcode.utils.SearcuUtils;
/**
* description: 搜索Controller
* @version v1.0
* @author w
* @date 2020年2月29日下午8:58:30
**/
@RestController
@RequestMapping(value = "/searchController")
public class SearchController {
@RequestMapping(value= "/search")
public String search(String key) {
List<String> search = SearcuUtils.search(key, SearcuUtils.loadWordList());
return StringUtils.join(search, ",") ;
}
}
三、测试
1、浏览器输入: http://localhost:8280/spring-mvc-tourist/searchController/search?key=rm
返回结果:中国人民,中华人民共和国
2、输入:http://localhost:8280/spring-mvc-tourist/searchController/search?key=中国
返回结果:中国,中国人民,我爱中国
四、总结
1、主要依赖于 ansj_seg 包,都具体实现都进行了封装,满足简单的需求是没问题的。
2、配合上前端,就可以实现一个简单的搜索自动匹配。