HanLP分词

官网地址:
https://github.com/hankcs/HanLP/releases/tag/v1.8.3

比较好的hanlp教学文章
https://blog.51cto.com/u_15344287/3649214
https://blog.51cto.com/u_15344287/category13/p_2

一.包上传

把下载的包hanlp-1.8.3-release.zip 解压后把hanlp-1.8.3.jar 部署的仓库中

mvn deploy:deploy-file -DgroupId=com.hankcs -DartifactId=hanlp -Dversion=1.8.3 -Dpackaging=jar -Dfile=D:/tool/hanLP/hanlp-1.8.3-release/hanlp-1.8.3.jar -Durl=http:/xxxxx/repository/3rd_party/ -DrepositoryId=3rd_party

二.文件配置

把data-for-1.7.5.zip解压后放到resources目录下面

在这里插入图片描述
hanlp.properties文件也放到resources目录下面。
配置root时,要注意路径。如果是单模块的springboot的项目,配置root=/src/main/resources
如果是多模块的springboot的项目,hanlp.properties文件在哪个子模块下,root=子模块名/src/main/resources

如果配置文件在search模块的resources下,那root=search/src/main/resources
CustomDictionaryPath 多个文件在同一个路径,中间要有个空格,以逗号分开

root=search/src/main/resources
CustomDictionaryPath=data/dictionary/custom/CustomDictionary.txt; my.txt;

如果是只用IDE开发,上面的配置就行了

当代码打成jar 部署到Linux或者容器中,会读取不到自定义的词典。

1.配置自定义的适配器HanLPResourcesAdapter
在这里插入图片描述
2.创建自定义适配器,create方法可以使用默认的,只是会在启动的时候有警告。找不到缓存文件CustomDictionary.txt.bin。
CustomDictionaryPath不管配置多少个自定义词典,会读取所有词典,然后只生成一个CustomDictionary.txt.bin缓存文件。
在自定义词典中增加了内容后,需要清理掉target中的CustomDictionary.txt.bin文件,或者重新package后,才会生效

import com.hankcs.hanlp.corpus.io.IIOAdapter;
import com.hankcs.hanlp.utility.Predefine;
import org.springframework.util.ClassUtils;

import java.io.*;

/**
 *
 */
public class HanLPResourcesAdapter implements IIOAdapter {
    @Override
    public InputStream open(String path) throws IOException {
       return HanLPResourcesAdapter.class.getClassLoader().getResourceAsStream(path);
    }

    /**
       https://github.com/hankcs/HanLP/issues/1788
     * 创建缓存文件  可以不实现,用默认的return new FileOutputStream(path);
     * @param path
     * @return
     * @throws IOException
     */
    @Override
    public OutputStream create(String path) throws IOException {
   
//      if (path.startsWith("data/")){
//            throw new IllegalArgumentException("不支持写入jar包资源路径" + path);
//        }
//        return new FileOutputStream(path);
        try{
            File file = new File(getClass().getClassLoader().getResource(path).toURI());
            OutputStream output = new FileOutputStream(file);
            return output;
        }catch (Exception e) {
            OutputStream output = new FileOutputStream(path);
            return output;
        }
    }
}

三.测试

测试下
在这里插入图片描述

在my.txt中匹配自定义词典后
在这里插入图片描述

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值