Python 敏感詞過濾的實(shí)現(xiàn)示例
一個(gè)簡單的實(shí)現(xiàn)
主要是通過循環(huán)和replace的方式進(jìn)行敏感詞的替換
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(寬度優(yōu)先搜索)進(jìn)行實(shí)現(xiàn)
對(duì)于搜索查找進(jìn)行了優(yōu)化,對(duì)于英語單詞,直接進(jìn)行了按詞索引字典查找。對(duì)于其他語言模式,我們采用逐字符查找匹配的一種模式。
BFS:寬度優(yōu)先搜索方式
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)進(jìn)行實(shí)現(xiàn)
DFA即Deterministic Finite Automaton,也就是確定有窮自動(dòng)機(jī)。
使用了嵌套的字典來實(shí)現(xiàn)。
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)
到此這篇關(guān)于Python 敏感詞過濾的實(shí)現(xiàn)示例的文章就介紹到這了,更多相關(guān)Python 敏感詞過濾內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Django2.1集成xadmin管理后臺(tái)所遇到的錯(cuò)誤集錦(填坑)
這篇文章主要介紹了Django2.1集成xadmin管理后臺(tái)所遇到的錯(cuò)誤集錦(填坑),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2018-12-12
使用Python可設(shè)置抽獎(jiǎng)?wù)邫?quán)重的抽獎(jiǎng)腳本代碼
這篇文章主要介紹了Python可設(shè)置抽獎(jiǎng)?wù)邫?quán)重的抽獎(jiǎng)腳本,抽獎(jiǎng)系統(tǒng)包含可給不同抽獎(jiǎng)?wù)咴O(shè)置不同的權(quán)重,先從價(jià)值高的獎(jiǎng)品開始抽,已經(jīng)中獎(jiǎng)的人,不再參與后續(xù)的抽獎(jiǎng),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-11-11
Python中SyntaxError: invalid syntax報(bào)錯(cuò)解決
在編寫Python代碼時(shí),常見的SyntaxError錯(cuò)誤通常由括號(hào)不匹配、關(guān)鍵字拼寫錯(cuò)誤或不正確的縮進(jìn)引起,本文詳細(xì)介紹了錯(cuò)誤原因及多種解決方案,包括檢查括號(hào)、關(guān)鍵字,以及使用IDE的語法檢查功能等,感興趣的可以了解一下2024-09-09
Python使用pypandoc將markdown文件和LaTex公式轉(zhuǎn)為word
pypandoc 是一個(gè)用于 pandoc 的輕量級(jí) Python 包裝器,支持多種格式的文檔轉(zhuǎn)換,下面我們來看看如何使用pypandoc將markdown文件和LaTex公式轉(zhuǎn)為word吧2025-04-04
python Selenium爬取內(nèi)容并存儲(chǔ)至MySQL數(shù)據(jù)庫的實(shí)現(xiàn)代碼
這篇文章主要介紹了python Selenium爬取內(nèi)容并存儲(chǔ)至MySQL數(shù)據(jù)庫的實(shí)現(xiàn)代碼,需要的朋友可以參考下2017-03-03
將tensorflow的ckpt模型存儲(chǔ)為npy的實(shí)例
今天小編就為大家分享一篇將tensorflow的ckpt模型存儲(chǔ)為npy的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-07-07

