基于DFA的敏感词检测和替换模块 SmallGFW
来源:互联网 发布:软件定义网络服务商 编辑:程序博客网 时间:2024/06/06 15:02
#encoding=utf-8
#DFA based text filter#author=sunjoy
#version=0.3
class GFW(object):
def __init__(self):
self.d = {}
#give a list of "ming gan ci"
def set(self,keywords):
p = self.d
q = {}
k = ''
for word in keywords:
word += chr(11)
p = self.d
for char in word:
char = char.lower()
if p=='':
q[k] = {}
p = q[k]
if not (char in p):
p[char] = ''
q = p
k = char
p = p[char]
pass
def replace(self,text,mask):
"""
>>> gfw = GFW()
>>> gfw.set(["sexy","girl","love","shit"])
>>> s = gfw.replace("Shit!,Cherry is a sexy girl. She loves python.","*")
>>> print s
*!,Cherry is a * *. She *s python.
"""
p = self.d
i = 0
j = 0
z = 0
result = []
ln = len(text)
while i+j<ln:
#print i,j
t = text[i+j].lower()
#print hex(ord(t))
if not (t in p):
j = 0
i += 1
p = self.d
continue
p = p[t]
j+=1
if chr(11) in p:
p = self.d
result.append(text[z:i])
result.append(mask)
i = i+j
z = i
j = 0
result.append(text[z:i+j])
return "".join(result)
def check(self,text):
"""
>>> gfw = GFW()
>>> gfw.set(["abd","defz","bcz"])
>>> print gfw.check("xabdabczabdxaadefz")
[(1, 3, 'abd'), (5, 3, 'bcz'), (8, 3, 'abd'), (14, 4, 'defz')]
"""
p = self.d
i = 0
j = 0
result = []
ln = len(text)
while i+j<ln:
t = text[i+j].lower()
#print i,j,hex(ord(t))
if not (t in p):
j = 0
i += 1
p = self.d
continue
p = p[t]
j+=1
#print p,i,j
if chr(11) in p:
p = self.d
result.append((i,j,text[i:i+j]))
i = i+j
j = 0
return result
if __name__=="__main__":
import doctest,sys
doctest.testmod(sys.modules[__name__])
smallgfw: 一个基于DFA的敏感词检测和替换模块,用法如doctest所示。
>>> gfw = GFW()
>>> gfw.set(["sexy","girl","love","shit"])#设置敏感词列表
>>> s = gfw.replace("shit!,Cherry is a sexy girl. She loves python.","*")
>>> print s
*!,Cherry is a * *. She *s python. #屏蔽后的效果
>>> gfw = GFW()
>>> gfw.set(["abd","defz","bcz"])
>>> print gfw.check("xabdabczabdxaadefz") #检测敏感词的出现位置
[(1, 3, 'abd'), (5, 3, 'bcz'), (8, 3, 'abd'), (14, 4, 'defz')] #例如,(5, 3, 'bcz')表示下标5之后长度为3的子串
from:http://www.oschina.net/p/smallgfw
0 0
- 基于DFA的敏感词检测和替换模块 SmallGFW
- smallgfw: 一个基于DFA的敏感词检测和替换模块。
- DFA算法过滤敏感词,替换为*
- DFA算法过滤敏感词,替换为*
- 敏感词替换,基于DFA算法,最快只需要读一遍文章即可完成替换敏感词,最差相当于读两遍文章
- 基于DFA敏感词查询的算法简析
- 基于DFA敏感词查询的算法简析
- 基于DFA算法实现过滤敏感词
- Java 敏感词替换-dfa算法,效率高
- php实现简单的基于DFA算法的敏感词过滤
- 基于DFA实现的敏感词过滤算法及在JFinal中的应用
- java DFA 敏感词过滤
- DFA敏感词过滤算法
- iOS敏感词过滤,DFA算法的OC实现
- Java 利用DFA算法 屏蔽敏感词
- DFA算法过滤敏感词整理
- Java 利用DFA算法 屏蔽敏感词
- Java DFA算法实现敏感词过滤
- 【python】遍历文件夹
- 解决用EasyDarwin开源流媒体服务器做HLS直播时Flash Player卡住的问题
- 成为Java GC专家(3)—如何优化Java垃圾回收机制
- 线程上下文切换的性能损耗测试
- 福利来了 Ubuntu14.04 配置 包含在Ubuntu里使用最新版QQ7.9
- 基于DFA的敏感词检测和替换模块 SmallGFW
- 排雷记录:Swift +Objective-C混合Framework的一些问题
- ie8下数据不显示,F12启动调试后正常
- ajax 跨域提示 重新载入页面以获取源代码
- oracle 触发器生成主键的
- Android编程——自定义View类onSaveInstanceState与onRestoreInstanceState使用方法
- 二项分布的实现(np.random.binomial)
- iOS 公司开发者账号邓白氏码申请
- CDbCriteria CArrayDataProvider zii.widgets.grid (2)