• 使用 Python 进行敏感词过滤


    环境

    • python 3.8

    • better_profanity 0.6.1

    前言

    本篇介绍一个敏感词过滤的工具,better-profanity,它是基于 Ben Friedland 开发的 profanity,在其基础上,由原来的基于正则的方法改成了现在的字符串比对,速度上提升了不少,同时支持拼写上的一些修改,如 b*tchp0rn 等,不过可惜的是,目前这个库还不支持中文。

    安装

    使用 pip 安装,执行命令

    pip install better_profanity==0.6.1

    这里安装的是 0.6.1 版本,并非目前最新的 0.7.0,原因是在新版本中存在性能问题,具体的情况可以去 https://github.com/snguyenthanh/better_profanity/issues/19 了解

    示例

    来看个最简单的例子

    1. from better_profanity import profanity
    2. if __name__ == "__main__":
    3.     profanity.load_censor_words()
    4.     text = "what a fcuk."
    5.     censored_text = profanity.censor(text)
    6.     print(censored_text)

    代码执行后,输出

    what a ****.

    load_censor_words 会去导入一个文本文件 profanity_wordlist.txt,这是默认的敏感词,模块会根据这些基础敏感词,使用特定的算法(可以去读源码 better_profanity.py),衍生出一些常见的变种写法,所以在实际使用中,这个算法也需要一直保持更新

    c173c1ef29924e466d55b98190a681f4.png

    发现敏感词后,默认会将目标字符串用4个 * 号来代替,当然,这个也是可以更改的

    1. from better_profanity import profanity
    2. if __name__ == "__main__":
    3.     text = "You p1ec3 of sHit."
    4.     censored_text = profanity.censor(text, '-')
    5.     print(censored_text)

    这样的话,就使用 - 来代替 *

    如果是自己来维护一个敏感词文件,也是支持的,使用方法也是非常简单

    1. from better_profanity import profanity
    2. if __name__ == "__main__":
    3.     profanity.load_censor_words_from_file('/path/to/my/project/my_wordlist.txt')

    如果想将某些词从敏感词中暂时剔除,可以使用白名单机制

    1. from better_profanity import profanity
    2. if __name__ == "__main__":
    3.     profanity.load_censor_words_from_file('/path/to/my/project/my_wordlist.txt', whitelist_words=['merry'])

    更多详细资料可以参考官方文档 https://pypi.org/project/better-profanity/

    Python实用模块专题

    更多有用的 python 模块,请移步

    https://xugaoxiang.com/category/python/modules/

  • 相关阅读:
    云原生下基于K8S声明式GitOps持续部署工具ArgoCD实战-上
    SM2签名算法中随机数K的随机性对算法安全的影响
    Java设计模式(三)结构型 设计模式
    Java虚拟机之运行时数据区(一)
    阿里云OSS对象存储
    Ubuntu是一个以桌面应用为主的Linux操作系统
    正则表达式简介
    笔记44:Batch_Normlization 过程详解
    初识JVM(简单易懂),解开JVM神秘的面纱
    【微信小程序开发(二)】自定义导航栏
  • 原文地址:https://blog.csdn.net/djstavaV/article/details/126458193