python 特殊词汇过滤功能的如何实现

python的其中一个强大之处就是它可以方便的集成很多的非标准库,今天在GitHub上溜达又发现了一个脏话处理神器,导入better_profanity库后,只

python的其中一个强大之处就是它可以方便的集成很多的非标准库,今天在GitHub上溜达又发现了一个脏话处理神器,导入better_profanity库后,只需要几行代码就能搞定了,相当nice!

使用pip的方式将better_profanity非标准库安装好,这个库好像在清华大学的镜像站中没有,其他镜像站不知道有没有,于是下载时没有使用镜像站,默认到官方去下载即可。

pip install better_profanity
# 将处理模块直接导入到代码块中
from better_profanity import profanity

1、默认脏话库/敏感词库处理

默认情况下就只能处理英文的脏话。

censored_text = profanity.censor("you are bitch",'-')
print(censored_text)
# you are ----

可以看到其中bitch字符被认为是脏话已经处理成****字符了。

当然,还可以将处理后的脏话字符换成别的字符代替,比如下面这样处理。

censored_text = profanity.censor("you are bitch",'-')
print(censored_text)
# you are ----

这样****就被替换成了----。

2、自定义过滤信息处理

bad_words = ['Python', 'Java', 'Scala']  # 自定义过滤词汇
profanity.load_censor_words(bad_words)  # 加载自定义过滤词汇
censored_text = profanity.censor("Python is very Good !")  # 执行过滤
print(censored_text)
# **** is very Good !

可以发现,想要过滤的python字符已经成功过滤掉了。

3、contains_profanity函数

contains_profanity函数用来查看我们的语句中是否包含需要过滤的词汇,如果包含则会返回True,否则返回False。

bad_words = ['bitch', 'Java', 'Scala']  # 自定义过滤词汇
profanity.load_censor_words(bad_words)  # 加载自定义过滤词汇
censored_text = profanity.contains_profanity("you are bitch")
print(censored_text)
# True

结果为True,表示包含需要过滤的词汇信息。

4、load_censor_words_from_file函数

load_censor_words_from_file函数用于加载需要过滤词汇的文件。

profanity.load_censor_words_from_file('/usr/load/bad_words.txt')

加载完词汇文件之后,按照之前的逻辑处理即可。

词汇文件的定义格式,按照每个词汇独占一行的形式进行定义,文件格式使用.txt文本文档即可。

# bitch
# bitches
# bitchin
# bitching
# blowjob
# blowjobs
# blue waffle

到此这篇关于python 脏话处理、特殊词汇过滤的文章就介绍到这了,更多相关python 特殊词汇过滤内容请搜索好代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好代码网!