【自然语言处理】Hanlp分词与去停用词工具

可以参考这个GitHub
分词除了使用jieba也可以用Hanlp的这个小工具,也很方便。

HanLP的词典分词实现

1.DoubleArrayTrieSegment

DoubleArrayTrieSegment分词器是对DAT最长匹配的封装,默认加载hanlp.properties中CoreDictionaryPath制定的词典。

from pyhanlp import *

# 不显示词性
HanLP.Config.ShowTermNature = False

# 可传入自定义字典 [dir1, dir2]
segment = DoubleArrayTrieSegment()
# 激活数字和英文识别
segment.enablePartOfSpeechTagging(True)

pyhanlp的安装和常见的python库安装方法一样,pip install pyhanlp
在第一次导入的时候会自动下载数据集,耗费时间较长

2.分词效果

在这里插入图片描述

3.去停用词

首先加载停用词词典,词典是一个包含了大部分停用词的txt文件,在源GitHub中可以下载

停用词文件

#加载停用词词典
def load_file(filename):
    with open(filename,'r',encoding="utf-8") as f:
        contents = f.readlines()
    result = []
    for content in contents:
        result.append(content.strip())
        
    return result

对生成的分词结果去掉停用词

#去停用词
def remove_stop_words(text,dic):
    result = []
    for k in text:
        if k.word not in dic:
            result.append(k.word)
    return result

去停用词后的效果
在这里插入图片描述

完整代码

from pyhanlp import *

HanLP.Config.ShowTermNature = False
segment = DoubleArrayTrieSegment()
segment.enablePartOfSpeechTagging(True)

#加载停用词词典
def load_file(filename):
    with open(filename,'r',encoding="utf-8") as f:
        contents = f.readlines()
    result = []
    for content in contents:
        result.append(content.strip())
        
    return result

#去停用词
def remove_stop_words(text,dic):
    result = []
    for k in text:
        if k.word not in dic:
            result.append(k.word)
    return result


text = segment.seg('江西鄱阳湖干枯了,中国最大的淡水湖变成了大草原')
print(text)
dic = load_file('stopwords.txt')
result = remove_stop_words(text,dic)
print(result)

在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章