搜索匹配
搜索匹配在日常的工作中很常见,最近在工作中发现 ansj 分词工具中有一个很好的工具可以用来进行搜索匹配,本篇博文将主要介绍这一工具的使用。
准备工作
首先你需要依赖 ansj-seg 这个包和仓库mvn-repo。示例如下:
<repositories>
<repository>
<id>mvn-repo</id>
<url>http://maven.nlpcn.org/</url>
</repository>
</repositories>
<dependency>
<groupId>org.ansj</groupId>
<artifactId>ansj_seg</artifactId>
<version>3.7.6</version>
</dependency>
我使用的 ansj_seg版本是3.7.6,你也可以去maven repository使用最新版本。
- 代码示例
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.nlpcn.commons.lang.index.MemoryIndex;
import org.nlpcn.commons.lang.pinyin.Pinyin;
import java.util.ArrayList;
import java.util.List;
/**
* Created by lionel on 16/11/16.
*/
public class SearchTest {
@Test
public void test() {
List<String> itemList = new ArrayList<String>();
itemList.add("中国");
itemList.add("美国");
itemList.add("dog");
itemList.add("China");
itemList.add("America");
itemList.add("我是中国人,我爱中国");
itemList.add("我是一个程序猿");
System.out.println(itemSearch("国", itemList));//[中国, 美国]
System.out.println(itemSearch("g",itemList));//[中国, 美国,dog, 我是一个程序猿, 我是中国人,我爱中国]
System.out.println(itemSearch("in",itemList));//[china]
System.out.println(itemSearch("A",itemList));//[America]
System.out.println(itemSearch("我",itemList));//[我是一个程序猿, 我是中国人,我爱中国]
System.out.println(itemSearch("wo",itemList));//[我是一个程序猿, 我是中国人,我爱中国]
}
private List<String> itemSearch(String key, List<String> itemList) {
MemoryIndex<String> memoryIndex = new MemoryIndex<String>();
if (StringUtils.isBlank(key) || itemList == null || itemList.size() == 0) {
return null;
}
for (String item : itemList) {
String fullChar = StringUtils.join(Pinyin.pinyin(item), "");
String firstChar = StringUtils.join(Pinyin.firstChar(item), "");
memoryIndex.addItem(item, item, fullChar, firstChar);
}
return memoryIndex.suggest(key);
}
}
从上面的代码是否能看出这个小工具的强大,无论我们输入中文,如”国”,”我”,都能匹配到对应的包含这个字的短语;当我们输入一个英文单词的中间部分是,如”in”,它还是能完美匹配到;更夸张的是,但我们输入”g”时,无论中文(中文会解析为对应的拼音)或者英文只要包含 g,都会显示出来,这就是我强烈推荐这个小工具的原因。
- 应用场景
下图就是我在应用中使用这个工具得到的效果部分截图。有兴趣的小伙伴可与自己动手实现下。