Python 敏感词过滤的实现示例
作者:waws520 时间:2021-07-04 12:17:28
目录
一个简单的实现
使用BSF(宽度优先搜索)进行实现
使用DFA(Deterministic Finite Automaton)进行实现
一个简单的实现
主要是通过循环和replace的方式进行敏感词的替换
class NaiveFilter():
'''Filter Messages from keywords
very simple filter implementation
>>> f = NaiveFilter()
>>> f.parse("filepath")
>>> f.filter("hello sexy baby")
hello **** baby
'''
def __init__(self):
self.keywords = set([])
def parse(self, path):
for keyword in open(path):
self.keywords.add(keyword.strip().decode('utf-8').lower())
def filter(self, message, repl="*"):
message = str(message).lower()
for kw in self.keywords:
message = message.replace(kw, repl)
return message
使用BSF(宽度优先搜索)进行实现
对于搜索查找进行了优化,对于英语单词,直接进行了按词索引字典查找。对于其他语言模式,我们采用逐字符查找匹配的一种模式。
BFS:宽度优先搜索方式
class BSFilter:
'''Filter Messages from keywords
Use Back Sorted Mapping to reduce replacement times
>>> f = BSFilter()
>>> f.add("sexy")
>>> f.filter("hello sexy baby")
hello **** baby
'''
def __init__(self):
self.keywords = []
self.kwsets = set([])
self.bsdict = defaultdict(set)
self.pat_en = re.compile(r'^[0-9a-zA-Z]+$') # english phrase or not
def add(self, keyword):
if not isinstance(keyword, str):
keyword = keyword.decode('utf-8')
keyword = keyword.lower()
if keyword not in self.kwsets:
self.keywords.append(keyword)
self.kwsets.add(keyword)
index = len(self.keywords) - 1
for word in keyword.split():
if self.pat_en.search(word):
self.bsdict[word].add(index)
else:
for char in word:
self.bsdict[char].add(index)
def parse(self, path):
with open(path, "r") as f:
for keyword in f:
self.add(keyword.strip())
def filter(self, message, repl="*"):
if not isinstance(message, str):
message = message.decode('utf-8')
message = message.lower()
for word in message.split():
if self.pat_en.search(word):
for index in self.bsdict[word]:
message = message.replace(self.keywords[index], repl)
else:
for char in word:
for index in self.bsdict[char]:
message = message.replace(self.keywords[index], repl)
return message
使用DFA(Deterministic Finite Automaton)进行实现
DFA即Deterministic Finite Automaton,也就是确定有穷自动机。
使用了嵌套的字典来实现。
class DFAFilter():
'''Filter Messages from keywords
Use DFA to keep algorithm perform constantly
>>> f = DFAFilter()
>>> f.add("sexy")
>>> f.filter("hello sexy baby")
hello **** baby
'''
def __init__(self):
self.keyword_chains = {}
self.delimit = '\x00'
def add(self, keyword):
if not isinstance(keyword, str):
keyword = keyword.decode('utf-8')
keyword = keyword.lower()
chars = keyword.strip()
if not chars:
return
level = self.keyword_chains
for i in range(len(chars)):
if chars[i] in level:
level = level[chars[i]]
else:
if not isinstance(level, dict):
break
for j in range(i, len(chars)):
level[chars[j]] = {}
last_level, last_char = level, chars[j]
level = level[chars[j]]
last_level[last_char] = {self.delimit: 0}
break
if i == len(chars) - 1:
level[self.delimit] = 0
def parse(self, path):
with open(path,encoding='UTF-8') as f:
for keyword in f:
self.add(keyword.strip())
def filter(self, message, repl="*"):
if not isinstance(message, str):
message = message.decode('utf-8')
message = message.lower()
ret = []
start = 0
while start < len(message):
level = self.keyword_chains
step_ins = 0
for char in message[start:]:
if char in level:
step_ins += 1
if self.delimit not in level[char]:
level = level[char]
else:
ret.append(repl * step_ins)
start += step_ins - 1
break
else:
ret.append(message[start])
break
else:
ret.append(message[start])
start += 1
return ''.join(ret)
来源:https://juejin.cn/post/7002068513070268424
标签:Python,敏感词,过滤
0
投稿
猜你喜欢
MySQL自定义序列数的实现方式
2024-01-14 00:09:50
webp 格式图片显示异常分析及解决方案
2023-08-26 22:33:27
在HTML中,常见的URL有多种表示方式:
2009-07-28 12:18:00
解剖JavaScript中的null和undefined
2009-03-01 12:49:00
JS重现80后儿时经典拼板(模板)游戏
2011-09-11 18:36:46
Django中QuerySet查询优化之prefetch_related详解
2022-02-03 04:18:44
Python中使用dom模块生成XML文件示例
2023-08-02 20:07:31
使用python+pygame开发消消乐游戏附完整源码
2021-06-26 03:42:52
js取得当前鼠标的X,Y坐标
2007-09-27 19:52:00
vue项目无法删除的问题及解决
2024-05-02 17:08:36
DBeaver一款替代Navicat的数据库可视化工具
2024-01-18 07:55:44
跨平台python异步回调机制实现和使用方法
2021-12-18 23:33:26
AJAX中文乱码解决
2009-07-03 13:43:00
Django实现CAS+OAuth2的方法示例
2023-01-26 17:32:46
python 中的jieba分词库
2023-08-10 01:26:30
微信小程序 scroll-view实现上拉加载与下拉刷新的实例
2024-04-23 09:30:40
机器学习的框架偏向于Python的13个原因
2023-09-28 06:24:42
简单方法实现Vue 无限滚动组件示例
2023-07-02 16:50:14
MySQL数据库的授权原则
2008-12-29 13:39:00
未知高度的图片垂直居中
2010-12-17 12:36:00