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

### 实现敏感词过滤的方法 #### 使用 `replace` 方法 最基础的方式是利用字符串的 `replace()` 函数逐一替换指定汇。这种方法适用于少量固定汇表的情况。 ```python def simple_replace(text, word_dict): for key in word_dict: text = text.replace(key, word_dict[key]) return text ``` 此方式虽然直观易懂,但在面对大量规则时效率较低[^1]。 #### 利用正则表达式库 `re` 通过编译正则表达式模式并应用到待检测文本上,能够一次性完成多个关键字的同时查找与替换工作。 ```python import re def regex_filter(text, pattern, replacement='*'): compiled_pattern = re.compile('|'.join(map(re.escape, pattern))) result = compiled_pattern.sub(replacement * 8, text) return result ``` 这种方式灵活性高,在处理复杂匹配条件方面具有优势[^2]。 #### DFA(Deterministic Finite Automaton)算法 DFA 是一种广泛应用于全文检索系统的高效多模态串匹配技术。它构建有限状态机模型来进行快速扫描操作。 ```python class DFATrieNode(object): def __init__(self): self.children = {} self.is_end_of_word = False class SensitiveWordFilter(object): def __init__(self): self.root = DFATrieNode() def add(self, keyword): node = self.root for char in keyword.lower(): if char not in node.children: new_node = DFATrieNode() node.children[char] = new_node node = node.children.get(char) node.is_end_of_word = True def search(self, content): current_state = self.root found_words = [] start_index = end_index = 0 while end_index < len(content): char = content[end_index].lower() if char in current_state.children: current_state = current_state.children[char] if current_state.is_end_of_word: bad_word = content[start_index:end_index + 1] found_words.append((bad_word, start_index)) # Reset to root after finding a match current_state = self.root end_index += 1 elif current_state != self.root and any(current_state.children.values()): continue else: start_index += 1 end_index = start_index current_state = self.root return found_words filter_instance = SensitiveWordFilter() for w in ['广告', '推广']: filter_instance.add(w) text_to_check = "这是一条包含广告的信息" matches = filter_instance.search(text_to_check) print(matches) ``` 该方案特别适合于实时性和准确性要求较高的场合[^4]。 #### 使用第三方库 `better-profanity` 为了简化开发流程,可以直接调用已有的成熟工具包如 better-profanity 来执行这项任务。 ```bash pip install better-profanity ``` ```python from better_profanity import profanity profanity.load_censor_words() # 加载默认脏话列表 censored_text = profanity.censor("This message contains some BAD WORDS") print(censored_text) ``` 这种途径不仅节省时间成本而且维护方便[^3]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

迷途小书童的Note

请博主喝矿泉书!

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

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

打赏作者

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

抵扣说明:

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

余额充值