python过滤敏感词汇_Python过滤敏感词汇
1.replace過濾
最簡單也是最直接的就是直接循環敏感詞,然后使用replace過濾關鍵詞,文章和敏感詞少的時候還可以,多的時候效率就真的很一般了。
2.使用正則過濾
有兩個技術要點,
1.使用Python正則表達式的re的sub()函數;
2.在正則表達式語法中,豎線“|”表示二選一或多選一。
代碼參考
Python
1
2
3
4
5
6
7
8
importre
defcheck_filter(keywords,text):
returnre.sub("|".join(keywords),"***",text)
keywords=("暴力","色情","其他關鍵字")
text="這句話里不包含暴力,也不包含色情,但是可能包含其他關鍵字"
print(check_filter(keywords,text))
返回結果
Python
1
2
這句話里不包含***,也不包含***,但是可能包含***
3.DFA過濾敏感詞算法
在網上查了下敏感詞過濾方案,找到了一種名為DFA的算法,即 Deterministic Finite Automaton 算法,翻譯成中文就是確定有窮自動機算法。它的基本思想是基于狀態轉移來檢索敏感詞,只需要掃描一次待檢測文本,就能對所有敏感詞進行檢測,所以效率比方案一高不少。
假設我們有以下5個敏感詞需要檢測:傻逼、傻子、傻大個、壞蛋、壞人。那么我們可以先把敏感詞中有相同前綴的詞組合成一個樹形結構,不同前綴的詞分屬不同樹形分支,以上述5個敏感詞為例,可以初始化成如下2棵樹:
把敏感詞組成成樹形結構有什么好處呢?最大的好處就是可以減少檢索次數,我們只需要遍歷一次待檢測文本,然后在敏感詞庫中檢索出有沒有該字符對應的子樹就行了,如果沒有相應的子樹,說明當前檢測的字符不在敏感詞庫中,則直接跳過繼續檢測下一個字符;如果有相應的子樹,則接著檢查下一個字符是不是前一個字符對應的子樹的子節點,這樣迭代下去,就能找出待檢測文本中是否包含敏感詞了。
我們以文本“你是不是傻逼”為例,我們依次檢測每個字符,因為前4個字符都不在敏感詞庫里,找不到相應的子樹,所以直接跳過。當檢測到“傻”字時,發現敏感詞庫中有相應的子樹,我們把他記為tree-1,接著再搜索下一個字符“逼”是不是子樹tree-1的子節點,發現恰好是,接下來再判斷“逼”這個字符是不是葉子節點,如果是,則說明匹配到了一個敏感詞了,在這里“逼”這個字符剛好是tree-1的葉子節點,所以成功檢索到了敏感詞:“傻逼”。大家發現了沒有,在我們的搜索過程中,我們只需要掃描一次被檢測文本就行了,而且對于被檢測文本中不存在的敏感詞,如這個例子中的“壞蛋”和“壞人”,我們完全不會掃描到,因此相比方案一效率大大提升了。
在python中,我們可以用dict來存儲上述的樹形結構,還是以上述敏感詞為例,我們把每個敏感詞字符串拆散成字符,再存儲到dict中,可以這樣存:
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
{
'傻':{
'逼':{
'\x00':0
},
'子':{
'\x00':0
},
'大':{
'個':{
'\x00':0
}
}
},
'壞':{
'蛋':{
'\x00':0
},
'人':{
'\x00':0}
}
}
首先將每個詞的第一個字符作為key,value則是另一個dict,value對應的dict的key為第二個字符,如果還有第三個字符,則存儲到以第二個字符為key的value中,當然這個value還是一個dict,以此類推下去,直到最后一個字符,當然最后一個字符對應的value也是dict,只不過這個dict只需要存儲一個結束標志就行了,像上述的例子中,我們就存了一個{'\x00': 0}的dict,來表示這個value對應的key是敏感詞的最后一個字符。
同理,“壞人”和“壞蛋”這2個敏感詞也是按這樣的方式存儲起來,這里就不羅列出來了。
用dict存儲有什么好處呢?我們知道dict在理想情況下可以以O(1)的時間復雜度進行查詢,所以我們在遍歷待檢測字符串的過程中,可以以O(1)的時間復雜度檢索出當前字符是否在敏感詞庫中,效率比方案一提升太多了。
接下來上代碼。
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# -*- coding:utf-8 -*-
importtime
time1=time.time()
# DFA算法
classDFAFilter(object):
def__init__(self):
self.keyword_chains={}# 關鍵詞鏈表
self.delimit='\x00'# 限定
defadd(self,keyword):
keyword=keyword.lower()# 關鍵詞英文變為小寫
chars=keyword.strip()# 關鍵字去除首尾空格和換行
ifnotchars:# 如果關鍵詞為空直接返回
return
level=self.keyword_chains
# 遍歷關鍵字的每個字
foriinrange(len(chars)):
# 如果這個字已經存在字符鏈的key中就進入其子字典
ifchars[i]inlevel:
level=level[chars[i]]
else:
ifnotisinstance(level,dict):
break
forjinrange(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
ifi==len(chars)-1:
level[self.delimit]=0
defparse(self,path):
withopen(path,encoding='utf-8')asf:
forkeywordinf:
self.add(str(keyword).strip())
print(self.keyword_chains)
deffilter(self,message,repl="*"):
message=message.lower()
ret=[]
start=0
whilestart
level=self.keyword_chains
step_ins=0
forchar inmessage[start:]:
ifchar inlevel:
step_ins+=1
ifself.delimit notinlevel[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)
if__name__=="__main__":
gfw=DFAFilter()
path="E:/lyh/test/sensitive_words.txt"
gfw.parse(path)
text="你真是個大傻逼,大傻子,傻大個,大壞蛋,壞人。"
result=gfw.filter(text)
print(text)
print(result)
time2=time.time()
print('總共耗時:'+str(time2-time1)+'s')
sensitive_words.txt
Python
1
2
3
4
5
6
傻逼
傻子
傻大個
壞蛋
壞人
運行結果
Python
1
2
3
4
你真是個大傻逼,大傻子,傻大個,大壞蛋,壞人。
你真是個大**,大**,***,大**,**。
總共耗時:0.0009999275207519531s
4.AC自動機過濾敏感詞算法
AC自動機:一個常見的例子就是給出n個單詞,再給出一段包含m個字符的文章,讓你找出有多少個單詞在文章里出現過。
簡單地講,AC自動機就是字典樹+kmp算法+失配指針
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# -*- coding:utf-8 -*-
importtime
time1=time.time()
# AC自動機算法
classnode(object):
def__init__(self):
self.next={}
self.fail=None
self.isWord=False
self.word=""
classac_automation(object):
def__init__(self):
self.root=node()
# 添加敏感詞函數
defaddword(self,word):
temp_root=self.root
forchar inword:
ifchar notintemp_root.next:
temp_root.next[char]=node()
temp_root=temp_root.next[char]
temp_root.isWord=True
temp_root.word=word
# 失敗指針函數
defmake_fail(self):
temp_que=[]
temp_que.append(self.root)
whilelen(temp_que)!=0:
temp=temp_que.pop(0)
p=None
forkey,value intemp.next.item():
iftemp==self.root:
temp.next[key].fail=self.root
else:
p=temp.fail
whilepisnotNone:
ifkey inp.next:
temp.next[key].fail=p.fail
break
p=p.fail
ifpisNone:
temp.next[key].fail=self.root
temp_que.append(temp.next[key])
# 查找敏感詞函數
defsearch(self,content):
p=self.root
result=[]
currentposition=0
whilecurrentposition
word=content[currentposition]
whileword inp.next==Falseandp!=self.root:
p=p.fail
ifword inp.next:
p=p.next[word]
else:
p=self.root
ifp.isWord:
result.append(p.word)
p=self.root
currentposition+=1
returnresult
# 加載敏感詞庫函數
defparse(self,path):
withopen(path,encoding='utf-8')asf:
forkeywordinf:
self.addword(str(keyword).strip())
# 敏感詞替換函數
defwords_replace(self,text):
"""
:param ah: AC自動機
:param text: 文本
:return: 過濾敏感詞之后的文本
"""
result=list(set(self.search(text)))
forxinresult:
m=text.replace(x,'*'*len(x))
text=m
returntext
if__name__=='__main__':
ah=ac_automation()
path='F:/文本反垃圾算法/sensitive_words.txt'
ah.parse(path)
text1="新疆騷亂蘋果新品發布會雞八"
text2=ah.words_replace(text1)
print(text1)
print(text2)
time2=time.time()
print('總共耗時:'+str(time2-time1)+'s')
運行結果
總結
以上是生活随笔為你收集整理的python过滤敏感词汇_Python过滤敏感词汇的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: for循环和数组练习
- 下一篇: python带参装饰器的改良版