使用 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 了解

示例

来看个最简单的例子

from better_profanity import profanity

if __name__ == "__main__":
    profanity.load_censor_words()

    text = "what a fcuk."
    censored_text = profanity.censor(text)
    print(censored_text)

代码执行后,输出

what a ****.

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

c173c1ef29924e466d55b98190a681f4.png

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

from better_profanity import profanity

if __name__ == "__main__":
    text = "You p1ec3 of sHit."

    censored_text = profanity.censor(text, '-')
    print(censored_text)

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

扫描二维码关注公众号,回复: 14813216 查看本文章

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

from better_profanity import profanity

if __name__ == "__main__":
    profanity.load_censor_words_from_file('/path/to/my/project/my_wordlist.txt')

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

from better_profanity import profanity

if __name__ == "__main__":
    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/

猜你喜欢

转载自blog.csdn.net/djstavaV/article/details/126458193