HanLP集成到Springboot及使用自定义词典

前言

HanLP集成到Springboot及使用自定义词典

文章目录

    • 前言
    • 简介
    • 集成Springboot
    • 扩展使用自定义词典
    • 路径易错问题

简介

开源工具包,提供词法分析、句法分析、文本分析和情感分析等功能,具有功能完善、性能高效、架构清晰、语料时新、可自定义等特点。

官网:https://www.hanlp.com/

开发文档:https://github.com/hankcs/HanLP/blob/1.x/README.md

集成Springboot

  1. Maven依赖引入

    <dependency>
                    <groupId>com.hankcsgroupId>
                    <artifactId>hanlpartifactId>
                    <version>portable-1.8.4version>
                dependency>
    
  2. 使用

    • 创建分词器:Segment segment = HanLP.newSegment()

    • 分词:List termList = segment.seg(sentence);

    • 根据词性提取需要的单词:词性类Nature

    • 示例,提取地名

      // 允许地名识别
      Segment segment = HanLP.newSegment().enablePlaceRecognize(true);
      List<Term> termList = segment.seg(sentence);
      // 过滤地名词性:
      List<String> list = termList.stream().filter(term -> Objects.equals(term.nature, Nature.ns)).map(term -> term.word).collect(Collectors.toList());
      

扩展使用自定义词典

由于内置的词典所包含的数据量不够大,因而某些单词词性的识别存在误差,需要引入更完善的字典库

  1. resources目录下增加配置文件hanlp.properties

  2. 配置自定义词典数据包

    # 根目录	
    root=
    # 自定义词典路径,相对于根目录的路径
    CustomDictionaryPath=data/dictionary/custom/CustomDictionary.txt;
    
  3. 引入词典数据包
    HanLP集成到Springboot及使用自定义词典_第1张图片

路径易错问题

  • 判断配置的目录下是否有核心词典库

    // 查看java根目录
    System.out.println(new File("").getAbsolutePath());
    // 查看hanlp根目录是否存在词典
    System.out.println(new File(HanLP.Config.CoreDictionaryPath).exists());
    
  • 项目代码打成jar包,需要将词典独立于jar包外

    # 自定义IO适配器(则可以使用相对hanlp配置文件的路径)
    IOAdapter=com.dotwith.framework.manager.MyIOAdapter
    
    # 根目录,词典所在的父级目录(window需改成本机
    root=hanlp
    
    # 自定义词典路径,相对于根目录的路径
    CustomDictionaryPath=data/dictionary/custom/CustomDictionary.txt;data/dictionary/custom/全国地名大全.txt ns
    
  • 使用相对路径:自定义IO适配器

    public class MyIOAdapter implements IIOAdapter {
    
        @Override
        public InputStream open(String path) throws IOException {
            System.out.println("path=" + this.getClass().getClassLoader().getResource(path).getFile());
            return new FileInputStream(this.getClass().getClassLoader().getResource(path).getFile());
        }
    
        @Override
        public OutputStream create(String path) throws IOException {
            return new FileOutputStream(this.getClass().getClassLoader().getResource(path).getFile());
        }
    }
    
  • 其他路径问题参考地址

    • https://github.com/hankcs/HanLP/pull/254
    • https://github.com/hankcs/HanLP/issues/935

你可能感兴趣的:(后端,spring,boot,后端,java,HanLP)