自然语言处理学习笔记(十)———— 停用词过滤

目录

1.停用词

2.实现思路

3.全部实现代码:

4.运行结果:


1.停用词

汉语中有一类没有多少意义的词语,比如助词"的"、连词"以及"、副词"甚至"、语气词"吧",称为停用词。一个句子去掉了停用词并不影响理解。停用词视具体任务的不同而不同,比如在网站系统中,一些非法的敏感词也视作停用词。因此,停用词过滤就是一个常见的预处理过程。

2.实现思路

考虑到词典中含有单字词语,用双数组词典树存储字典更划算:

python 复制代码
def load_from_file(path):
    """
    从词典文件加载DoubleArrayTrie
    :param path: 词典路径
    :return: 双数组trie树
    """
    map = JClass('java.util.TreeMap')()  # 创建TreeMap实例
    with open(path, encoding='utf-8') as src:
        for word in src:
            word = word.strip()  # 去掉Python读入的\n
            map[word] = word
    return JClass('com.hankcs.hanlp.collection.trie.DoubleArrayTrie')(map)


def load_from_words(*words):
    """
    从词汇构造双数组trie树
    :param words: 一系列词语
    :return:
    """
    map = JClass('java.util.TreeMap')()  # 创建TreeMap实例
    for word in words:
        map[word] = word
    return JClass('com.hankcs.hanlp.collection.trie.DoubleArrayTrie')(map)

加载停用词后,会得到一颗双数组字典树。针对分词结果,遍历每个词语,若他在字典树中,则删除。

python 复制代码
def remove_stopwords_termlist(termlist, trie):
    return [term.word for term in termlist if not trie.containsKey(term.word)]

在敏感词过滤的场景下,通常需要将敏感词替换为特殊字符串,如***,可以先分词在替换,也可以不分词直接利用接口查找敏感词并完成替换。

python 复制代码
def replace_stropwords_text(text, replacement, trie):
    searcher = trie.getLongestSearcher(JString(text), 0)
    offset = 0
    result = ''
    while searcher.next():
        begin = searcher.begin
        end = begin + searcher.length
        if begin > offset:
            result += text[offset: begin]
        result += replacement
        offset = end
    if offset < len(text):
        result += text[offset:]
    return result

3.全部实现代码:

python 复制代码
from jpype import JString

from pyhanlp import *


def load_from_file(path):
    """
    从词典文件加载DoubleArrayTrie
    :param path: 词典路径
    :return: 双数组trie树
    """
    map = JClass('java.util.TreeMap')()  # 创建TreeMap实例
    with open(path, encoding='utf-8') as src:
        for word in src:
            word = word.strip()  # 去掉Python读入的\n
            map[word] = word
    return JClass('com.hankcs.hanlp.collection.trie.DoubleArrayTrie')(map)


def load_from_words(*words):
    """
    从词汇构造双数组trie树
    :param words: 一系列词语
    :return:
    """
    map = JClass('java.util.TreeMap')()  # 创建TreeMap实例
    for word in words:
        map[word] = word
    return JClass('com.hankcs.hanlp.collection.trie.DoubleArrayTrie')(map)


def remove_stopwords_termlist(termlist, trie):
    return [term.word for term in termlist if not trie.containsKey(term.word)]


def replace_stropwords_text(text, replacement, trie):
    searcher = trie.getLongestSearcher(JString(text), 0)
    offset = 0
    result = ''
    while searcher.next():
        begin = searcher.begin
        end = begin + searcher.length
        if begin > offset:
            result += text[offset: begin]
        result += replacement
        offset = end
    if offset < len(text):
        result += text[offset:]
    return result


if __name__ == '__main__':
    HanLP.Config.ShowTermNature = False
    trie = load_from_file(HanLP.Config.CoreStopWordDictionaryPath)
    text = "停用词的意义相对而言无关紧要吧。"
    segment = DoubleArrayTrieSegment()
    termlist = segment.seg(text)
    print("分词结果:", termlist)
    print("分词结果去除停用词:", remove_stopwords_termlist(termlist, trie))
    trie = load_from_words("的", "相对而言", "吧")
    print("不分词去掉停用词", replace_stropwords_text(text, "**", trie))

4.运行结果:

分词结果:[停用,词,的,意义,相对而言,无关紧要,吧,。]

分词结果去掉停用词:[停用,词,意义,无关紧要]

不分词去掉停用词:停用词**意义**无关紧要**。

相关推荐
老百姓懂点AI6 分钟前
[WASM实战] 插件系统的安全性:智能体来了(西南总部)AI调度官的WebAssembly沙箱与AI agent指挥官的动态加载
人工智能·wasm
人工智能训练7 小时前
【极速部署】Ubuntu24.04+CUDA13.0 玩转 VLLM 0.15.0:预编译 Wheel 包 GPU 版安装全攻略
运维·前端·人工智能·python·ai编程·cuda·vllm
源于花海7 小时前
迁移学习相关的期刊和会议
人工智能·机器学习·迁移学习·期刊会议
微露清风8 小时前
系统性学习Linux-第二讲-基础开发工具
linux·运维·学习
不会代码的小猴8 小时前
Linux环境编程第六天笔记--system-V IPC
linux·笔记
阳光九叶草LXGZXJ8 小时前
达梦数据库-学习-48-DmDrs控制台命令(同步之Manager、CPT模块)
linux·运维·数据库·sql·学习
DisonTangor9 小时前
DeepSeek-OCR 2: 视觉因果流
人工智能·开源·aigc·ocr·deepseek
乌恩大侠9 小时前
【笔记】USRP 5G 和 6G 参考架构
笔记·5g
薛定谔的猫19829 小时前
二十一、基于 Hugging Face Transformers 实现中文情感分析情感分析
人工智能·自然语言处理·大模型 训练 调优
发哥来了9 小时前
《AI视频生成技术原理剖析及金管道·图生视频的应用实践》
人工智能