【python 走進NLP】兩種高效過濾敏感詞演算法--DFA演算法和AC自動機演算法
阿新 • • 發佈:2018-11-03
一道bat面試題:快速替換10億條標題中的5萬個敏感詞,有哪些解決思路?
有十億個標題,存在一個檔案中,一行一個標題。有5萬個敏感詞,存在另一個檔案。寫一個程式過濾掉所有標題中的所有敏感詞,儲存到另一個檔案中。
1、DFA過濾敏感詞演算法
在實現文字過濾的演算法中,DFA是比較好的實現演算法。DFA即Deterministic Finite Automaton,也就是確定有窮自動機。
演算法核心是建立了以敏感詞為基礎的許多敏感詞樹。
python 實現DFA演算法:
# -*- coding:utf-8 -*- import time time1=time.time() # DFA演算法 class DFAFilter(): def __init__(self): self.keyword_chains = {} self.delimit = '\x00' def add(self, keyword): 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(str(keyword).strip()) def filter(self, message, repl="*"): 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) if __name__ == "__main__": gfw = DFAFilter() path="F:/文字反垃圾演算法/sensitive_words.txt" gfw.parse(path) text="新疆騷亂蘋果新品釋出會雞八" result = gfw.filter(text) print(text) print(result) time2 = time.time() print('總共耗時:' + str(time2 - time1) + 's')
執行效果:
E:\laidefa\python.exe "E:/Program Files/pycharmproject/敏感詞過濾演算法/敏感詞過濾演算法DFA.py"
新疆騷亂蘋果新品釋出會雞八
****蘋果新品釋出會**
總共耗時:0.0010344982147216797s
Process finished with exit code 0
2、AC自動機過濾敏感詞演算法
AC自動機:一個常見的例子就是給出n個單詞,再給出一段包含m個字元的文章,讓你找出有多少個單詞在文章裡出現過。
簡單地講,AC自動機就是字典樹+kmp演算法+失配指標
# -*- coding:utf-8 -*- import time time1=time.time() # AC自動機演算法 class node(object): def __init__(self): self.next = {} self.fail = None self.isWord = False self.word = "" class ac_automation(object): def __init__(self): self.root = node() # 新增敏感詞函式 def addword(self, word): temp_root = self.root for char in word: if char not in temp_root.next: temp_root.next[char] = node() temp_root = temp_root.next[char] temp_root.isWord = True temp_root.word = word # 失敗指標函式 def make_fail(self): temp_que = [] temp_que.append(self.root) while len(temp_que) != 0: temp = temp_que.pop(0) p = None for key,value in temp.next.item(): if temp == self.root: temp.next[key].fail = self.root else: p = temp.fail while p is not None: if key in p.next: temp.next[key].fail = p.fail break p = p.fail if p is None: temp.next[key].fail = self.root temp_que.append(temp.next[key]) # 查詢敏感詞函式 def search(self, content): p = self.root result = [] currentposition = 0 while currentposition < len(content): word = content[currentposition] while word in p.next == False and p != self.root: p = p.fail if word in p.next: p = p.next[word] else: p = self.root if p.isWord: result.append(p.word) p = self.root currentposition += 1 return result # 載入敏感詞庫函式 def parse(self, path): with open(path,encoding='utf-8') as f: for keyword in f: self.addword(str(keyword).strip()) # 敏感詞替換函式 def words_replace(self, text): """ :param ah: AC自動機 :param text: 文字 :return: 過濾敏感詞之後的文字 """ result = list(set(self.search(text))) for x in result: m = text.replace(x, '*' * len(x)) text = m return text 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')
E:\laidefa\python.exe "E:/Program Files/pycharmproject/敏感詞過濾演算法/AC自動機過濾敏感詞演算法.py"
新疆騷亂蘋果新品釋出會雞八
****蘋果新品釋出會**
總共耗時:0.0010304450988769531s
Process finished with exit code 0
3、java 實現參考連結:
https://www.cnblogs.com/AlanLee/p/5329555.html