Python實(shí)現(xiàn)敏感詞過濾的五種方法
1、replace替換
replace就是最簡(jiǎn)單的字符串替換,當(dāng)一串字符串中有可能會(huì)出現(xiàn)的敏感詞時(shí),我們直接使用相應(yīng)的replace方法用*替換出敏感詞即可。
缺點(diǎn):
文本和敏感詞少的時(shí)候還可以,多的時(shí)候效率就比較差了。
示例代碼:
text = '我是一個(gè)來(lái)自星星的超人,具有超人本領(lǐng)!'
text = text.replace("超人", '*' * len("超人")).replace("星星", '*' * len("星星"))
print(text) # 我是一個(gè)來(lái)自***的***,具有***本領(lǐng)!運(yùn)行結(jié)果:

如果是多個(gè)敏感詞可以用列表進(jìn)行逐一替換。
示例代碼:
text = '我是一個(gè)來(lái)自星星的超人,具有超人本領(lǐng)!'
words = ['超人', '星星']
for word in words:
text = text.replace(word, '*' * len(word))
print(text) # 我是一個(gè)來(lái)自***的***,具有***本領(lǐng)!運(yùn)行效果:

2、正則表達(dá)式
使用正則表達(dá)式是一種簡(jiǎn)單而有效的方法,可以快速地匹配敏感詞并進(jìn)行過濾。在這里我們主要是使用“|”來(lái)進(jìn)行匹配,“|”的意思是從多個(gè)目標(biāo)字符串中選擇一個(gè)進(jìn)行匹配。
示例代碼:
import re
def filter_words(text, words):
pattern = '|'.join(words)
return re.sub(pattern, '***', text)
if __name__ == '__main__':
text = '我是一個(gè)來(lái)自星星的超人,具有超人本領(lǐng)!'
words = ['超人', '星星']
res = filter_words(text, words)
print(res) # 我是一個(gè)來(lái)自***的***,具有***本領(lǐng)!運(yùn)行結(jié)果:

3、使用ahocorasick第三方庫(kù)
ahocorasick庫(kù)安裝:
pip install pyahocorasick

示例代碼:
import ahocorasick
def filter_words(text, words):
A = ahocorasick.Automaton()
for index, word in enumerate(words):
A.add_word(word, (index, word))
A.make_automaton()
result = []
for end_index, (insert_order, original_value) in A.iter(text):
start_index = end_index - len(original_value) + 1
result.append((start_index, end_index))
for start_index, end_index in result[::-1]:
text = text[:start_index] + '*' * (end_index - start_index + 1) + text[end_index + 1:]
return text
if __name__ == '__main__':
text = '我是一個(gè)來(lái)自星星的超人,具有超人本領(lǐng)!'
words = ['超人', '星星']
res = filter_words(text, words)
print(res) # 我是一個(gè)來(lái)自***的***,具有***本領(lǐng)!運(yùn)行結(jié)果:

4、字典樹
使用字典樹是一種高效的方法,可以快速地匹配敏感詞并進(jìn)行過濾。
示例代碼:
class TreeNode:
def __init__(self):
self.children = {}
self.is_end = False
class Tree:
def __init__(self):
self.root = TreeNode()
def insert(self, word):
node = self.root
for char in word:
if char not in node.children:
node.children[char] = TreeNode()
node = node.children[char]
node.is_end = True
def search(self, word):
node = self.root
for char in word:
if char not in node.children:
return False
node = node.children[char]
return node.is_end
def filter_words(text, words):
tree = Tree()
for word in words:
tree.insert(word)
result = []
for i in range(len(text)):
node = tree.root
for j in range(i, len(text)):
if text[j] not in node.children:
break
node = node.children[text[j]]
if node.is_end:
result.append((i, j))
for start_index, end_index in result[::-1]:
text = text[:start_index] + '*' * (end_index - start_index + 1) + text[end_index + 1:]
return text
if __name__ == '__main__':
text = '我是一個(gè)來(lái)自星星的超人,具有超人本領(lǐng)!'
words = ['超人', '星星']
res = filter_words(text, words)
print(res) # 我是一個(gè)來(lái)自***的***,具有***本領(lǐng)!運(yùn)行結(jié)果:

5、DFA算法
使用DFA算法是一種高效的方法,可以快速地匹配敏感詞并進(jìn)行過濾。DFA的算法,即Deterministic Finite Automaton算法,翻譯成中文就是確定有窮自動(dòng)機(jī)算法。它的基本思想是基于狀態(tài)轉(zhuǎn)移來(lái)檢索敏感詞,只需要掃描一次待檢測(cè)文本,就能對(duì)所有敏感詞進(jìn)行檢測(cè)。
示例代碼:
class DFA:
def __init__(self, words):
self.words = words
self.build()
def build(self):
self.transitions = {}
self.fails = {}
self.outputs = {}
state = 0
for word in self.words:
current_state = 0
for char in word:
next_state = self.transitions.get((current_state, char), None)
if next_state is None:
state += 1
self.transitions[(current_state, char)] = state
current_state = state
else:
current_state = next_state
self.outputs[current_state] = word
queue = []
for (start_state, char), next_state in self.transitions.items():
if start_state == 0:
queue.append(next_state)
self.fails[next_state] = 0
while queue:
r_state = queue.pop(0)
for (state, char), next_state in self.transitions.items():
if state == r_state:
queue.append(next_state)
fail_state = self.fails[state]
while (fail_state, char) not in self.transitions and fail_state != 0:
fail_state = self.fails[fail_state]
self.fails[next_state] = self.transitions.get((fail_state, char), 0)
if self.fails[next_state] in self.outputs:
self.outputs[next_state] += ', ' + self.outputs[self.fails[next_state]]
def search(self, text):
state = 0
result = []
for i, char in enumerate(text):
while (state, char) not in self.transitions and state != 0:
state = self.fails[state]
state = self.transitions.get((state, char), 0)
if state in self.outputs:
result.append((i - len(self.outputs[state]) + 1, i))
return result
def filter_words(text, words):
dfa = DFA(words)
result = []
for start_index, end_index in dfa.search(text):
result.append((start_index, end_index))
for start_index, end_index in result[::-1]:
text = text[:start_index] + '*' * (end_index - start_index + 1) + text[end_index + 1:]
return text
if __name__ == '__main__':
text = '我是一個(gè)來(lái)自星星的超人,具有超人本領(lǐng)!'
words = ['超人', '星星']
res = filter_words(text, words)
print(res) # 我是一個(gè)來(lái)自***的***,具有***本領(lǐng)!運(yùn)行結(jié)果:

到此這篇關(guān)于Python實(shí)現(xiàn)敏感詞過濾的五種方法的文章就介紹到這了,更多相關(guān)Python敏感詞過濾內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python中常用信號(hào)signal類型實(shí)例
這篇文章主要介紹了Python中常用信號(hào)signal類型實(shí)例,分享了相關(guān)代碼示例,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01
pycharm顯示遠(yuǎn)程圖片的實(shí)現(xiàn)
這篇文章主要介紹了pycharm顯示遠(yuǎn)程圖片的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11
Python輕松實(shí)現(xiàn)在Excel工作表中應(yīng)用條件格式
在日常數(shù)據(jù)處理工作中,條件格式是一項(xiàng)非常實(shí)用的功能,本文將介紹如何使用 Python 和 Spire.XLS 庫(kù)在 Excel 工作表中應(yīng)用多種類型的條件格式,有需要的小伙伴庫(kù)參考下2026-05-05
pandas讀取csv文件,分隔符參數(shù)sep的實(shí)例
今天小編就為大家分享一篇pandas讀取csv文件,分隔符參數(shù)sep的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來(lái)看看吧2018-12-12
python對(duì)常見數(shù)據(jù)類型的遍歷解析
這篇文章主要介紹了python對(duì)常見數(shù)據(jù)類型的遍歷解析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-08-08
Python高效實(shí)現(xiàn)CSV數(shù)據(jù)轉(zhuǎn)換為規(guī)范的Excel文件
在當(dāng)今數(shù)據(jù)驅(qū)動(dòng)的世界中,CSV(逗號(hào)分隔值)和Excel(電子表格)是兩種最常見的數(shù)據(jù)存儲(chǔ)和交換格式,本文將深入探討如何使用一個(gè)強(qiáng)大的Python庫(kù),將CSV文件高效地轉(zhuǎn)換為結(jié)構(gòu)化且美觀的Excel文件,感興趣的小伙伴可以了解下2026-01-01
python中對(duì)開區(qū)間和閉區(qū)間的理解
這篇文章主要介紹了python中對(duì)開區(qū)間和閉區(qū)間的理解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-07-07

