Python类实现敏感词过滤:递归处理嵌套替换方案
本文介绍如何使用Python类封装敏感词过滤功能,重点解决替换后新生成敏感词的嵌套问题。通过递归调用替换方法,持续处理字符串直到结果不再变化。文章包含敏感词库构建、核心代码实现及运行流程,适合需要文本内容安全过滤的开发者参考。
递归处理嵌套敏感词逻辑
当执行一次过滤替换后,剩余字符串中可能组合出新的敏感词。针对这种情况,需要采用递归机制进行处理,持续执行过滤替换操作,直到某次处理后的结果与处理前完全一致时,才判定过滤流程结束。
构建敏感词库文件
首先,需要建立一个敏感词库,通常保存为.txt格式的文本文件,用于存储待过滤的敏感词汇。

接下来编写Python代码,在文章中实现敏感词的过滤功能,核心逻辑通过递归方式实现。
Python类实现代码详解
# -*- coding: utf-8 -*-
# author 代序春秋
import os
import chardet
# 获取文件目录和绝对路径
curr_dir = os.path.dirname(os.path.abspath(__file__))
# os.path.join()拼接路径
sensitive_word_stock_path = os.path.join(curr_dir, 'sensitive_word_stock.txt')
# 获取存放敏感字库的路径
# print(sensitive_word_stock_path)
class ArticleFilter(object):
# 实现文章敏感词过滤
def filter_replace(self, string):
# string = string.decode("gbk")
# 存放敏感词的列表
filtered_words = []
# 打开敏感词库读取敏感字
with open(sensitive_word_stock_path) as filtered_words_txt:
lines = filtered_words_txt.readlines()
for line in lines:
# strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
filtered_words.append(line.strip())
# 输出过滤好之后的文章
print("过滤之后的文字:" + self.replace_words(filtered_words, string))
# 实现敏感词的替换,替换为*
def replace_words(self, filtered_words, string):
# 保留新字符串
new_string = string
# 从列表中取出敏感词
for words in filtered_words:
# 判断敏感词是否在文章中
if words in string:
# 如果在则用*替换(几个字替换几个*)
new_string = string.replace(words, "*" * len(words))
# 当替换好的文章(字符串)与被替换的文章(字符串)相同时,结束递归,返回替换好的文章(字符串)
if new_string == string:
# 返回替换好的文章(字符串)
return new_string
# 如果不相同则继续替换(递归函数自己调用自己)
else:
# 递归函数自己调用自己
return self.replace_words(filtered_words, new_string)
def main():
while True:
string = input("请输入一段文字:")
run = ArticleFilter()
run.filter_replace(string)
continue
if __name__ == '__main__':
main()
运行结果展示
程序运行后的输出结果如下所示。

以上即为本文分享的全部内容,希望能为读者的学习带来帮助,同时也欢迎大家继续支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









