Java-搜索匹配

搜索匹配

搜索匹配在日常的工作中很常见,最近在工作中发现 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,都会显示出来,这就是我强烈推荐这个小工具的原因。

  • 应用场景

下图就是我在应用中使用这个工具得到的效果部分截图。有兴趣的小伙伴可与自己动手实现下。
这里写图片描述
这里写图片描述
这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值