使用 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)

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

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

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/

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

迷途小书童的Note

请博主喝矿泉书!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值