zoukankan      html  css  js  c++  java
  • 由于在pyhanlp中使用load_dictionary没有作用,亲测一种实际有效的方法

    一、看到相关教程,有一个添加字典的方法,亲测无效:

     1 # -*- coding:utf-8 -*-
     2 # Author:hankcs
     3 # Date: 2018-05-24 22:11
     4 # 《自然语言处理入门》2.2.2 词典的加载
     5 # 配套书籍:http://nlp.hankcs.com/book.php
     6 # 讨论答疑:https://bbs.hankcs.com/
     7 from pyhanlp import *
     8 
     9 
    10 def load_dictionary():
    11     """
    12     加载HanLP中的mini词库
    13     :return: 一个set形式的词库
    14     """
    15     IOUtil = JClass('com.hankcs.hanlp.corpus.io.IOUtil')
    16     path = HanLP.Config.CoreDictionaryPath.replace('.txt', '.mini.txt')
    17     print(path)
    18     dic = IOUtil.loadDictionary([path])
    19     return set(dic.keySet())
    20 
    21 
    22 if __name__ == '__main__':
    23     dic = load_dictionary()
    24     print(len(dic))
    25     print(list(dic)[0])

    其实也不是没有效果,运行这个代码,是可行的,但是换到自定义的字典就无效,稍后解释其中的原因。

    二:解决办法:

    第一步:

    更改hanlp.properties文件配置:

    值得注意的是:

    1 CustomDictionaryPath=data/dictionary/custom/CustomDictionary.txt; 现代汉语补充词库.txt; 全国地名大全.txt ns; 人名词典.txt; 机构名词典.txt; 上海地名.txt ns;data/dictionary/person/nrf.txt nrf;data/dictionary/Tinghua/animal.txt nz; area.txt ns; car.txt nz; chengyu.txt nz; finance.txt nf; food.txt nz; history_people.txt nr; it.txt nz; law.txt nz; medical.txt nz; poem.txt nz;

    同一路径,只用分号空格相隔,不同路径,需要重新写

    然后删除CustomDictionary.txt.bin文件

    删除之后,在运行就可以了

    同时要注意,字典有个格式,一定是空格间隔,千万不要有 间隔。

    总结:解释原因

    为什么官网给的就可以用,而我们自定义的就不能用了呢?

    主要原因是他已经配置过了,所以才可以用,只要按照上面的路数,走一遍,就也可以了。

    这里还有一些动态的方法:

     1 def demo_custom_dictionary(text):
     2     """ 演示用户词典的动态增删
     3     TO-DO:
     4     DoubleArrayTrie分词
     5     首字哈希之后二分的trie树分词
     6 
     7     [攻城/vi, 狮/ng, 逆袭/nz, 单身/n, 狗/n, ,/w, 迎娶/v, 白富美/nr, ,/w, 走上/v, 人生/n, 巅峰/n]
     8     [攻城狮/nz, 逆袭/nz, 单身狗/nz, ,/w, 迎娶/v, 白富美/nz, ,/w, 走上/v, 人生/n, 巅峰/n]
     9     """
    10     #print(HanLP.segment(text))
    11 
    12     #CustomDictionary = JClass("com.hankcs.hanlp.dictionary.CustomDictionary")
    13     #CustomDictionary.add("Android图片处理")  # 动态增加
    14     # CustomDictionary.insert("白富美", "nz 1024")  # 强行插入
    15     # #CustomDictionary.remove("攻城狮"); # 删除词语(注释掉试试)
    16     # CustomDictionary.add("单身狗", "nz 1024 n 1")
    17     # #print(CustomDictionary.get("单身狗"))
    18     print(HanLP.segment(text))
  • 相关阅读:
    TTTTTTTTTTTTTTTTTTT UVA 2045 Richness of words
    hdu 5723 Abandoned country 最小生成树+子节点统计
    hdu 5792 World is Exploding 树状数组+离散化+容斥
    MySQL字符集详解
    MySQL的sql语言分类DML、DQL、DDL、DCL、
    MySQL5.6的4个自带库详解
    Win10下安装MySQL5.6
    {MySQL数据库初识}一 数据库概述 二 MySQL介绍 三 MySQL的下载安装、简单应用及目录介绍 四 root用户密码设置及忘记密码的解决方案 五 修改字符集编码 六 初识sql语句
    {python--GIL锁}一 介绍 二 GIL介绍 三 GIL与Lock 四 GIL与多线程 五 多线程性能测试
    Navicat安装及简单使用
  • 原文地址:https://www.cnblogs.com/smartisn/p/13921999.html
Copyright © 2011-2022 走看看