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分词_第1张图片
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
HanLP分词_第2张图片
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;
        }
    }
}

三.测试

测试下
HanLP分词_第3张图片

在my.txt中匹配自定义词典后
HanLP分词_第4张图片

HanLP分词_第5张图片

你可能感兴趣的:(ELK,java,spring,boot)