9

Python实用模块(三十四)better-profanity

 2 years ago
source link: https://xugaoxiang.com/2022/08/19/python-module-34-better-profanity/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
  • 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),衍生出一些常见的变种写法,所以在实际使用中,这个算法也需要一直保持更新

000348a3b175312d.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/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK