前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >HanLP-停用词表的使用示例

HanLP-停用词表的使用示例

作者头像
IT小白龙
修改2019-05-22 18:01:58
1.9K0
修改2019-05-22 18:01:58
举报
文章被收录于专栏:hadoop学习笔记

停用词表的修改

停用词表在“pyhanlp\static\data\dictionary”路径下的“stopwords.txt”文件中,CoreStopWordDictionary.apply方法支持去除停用词。如果需要修改停用词表,则直接编辑文件“stopwords.txt”,之后删除路径下的“stopwords.txt.bin”,运行CoreStopWordDictionary.apply后即可自动生效。有关验证的方法见“验证是否生效”小节。

自定义词语过滤方法

用户可以通过编写“pyhanlp\static”路径下的“MyFilter.java”文件设置自己的词语过滤方法。应当注意这里处理的语言单位是词语,而不是字。编辑完毕后需要编译该文件并生成字节码文件,之后运行CoreStopWordDictionary.apply方法时就会自动调用用户自己的词语过滤方法了。这里给出一个自定义过滤方法的编写示例代码。

代码语言:javascript
复制
import os
from pyhanlp.static import STATIC_ROOT, HANLP_JAR_PATH
java_code_path = os.path.join(STATIC_ROOT, 'MyFilter.java')
with open(java_code_path, 'w') as out:
    java_code = """
import com.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary;
import com.hankcs.hanlp.dictionary.stopword.Filter;
import com.hankcs.hanlp.seg.common.Term;
public class MyFilter implements Filter
{
    public boolean shouldInclude(Term term)
    {
        if (term.nature.startsWith('m')) return false; // 数词过滤
        if (term.nature.startsWith('q')) return false; // 量词过滤
        if (term.nature.startsWith('t')) return false; // 时间词过滤
        if (term.nature.startsWith("w")) return false; // 过滤标点符号
        return !CoreStopWordDictionary.contains(term.word); // 停用词过滤
    }
}
"""
    out.write(java_code)
os.system('javac -cp {} {} -d {}'.format(HANLP_JAR_PATH, java_code_path, STATIC_ROOT))

验证是否生效

本节给出停用词表修改后以及使用了自定义词语过滤方法的示例代码。

代码语言:javascript
复制
from pyhanlp import *

# 加载停用词类

代码语言:javascript
复制
CoreStopWordDictionary = JClass("com.hankcs.hanlp.dictionary.stopword.CoreStopWordDictionary")

# 加载自定义词语过滤逻辑

代码语言:javascript
复制
MyFilter = JClass('MyFilter')
CoreStopWordDictionary.FILTER = MyFilter()
term_list = HanLP.segment(text)
CoreStopWordDictionary.apply(term_list)

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档