python實(shí)現(xiàn)過濾敏感詞
簡述:
關(guān)于敏感詞過濾可以看成是一種文本反垃圾算法,例如
題目:敏感詞文本文件 filtered_words.txt,當(dāng)用戶輸入敏感詞語,則用 星號 * 替換,例如當(dāng)用戶輸入「北京是個(gè)好城市」,則變成「**是個(gè)好城市」
代碼:
#coding=utf-8 def filterwords(x): with open(x,'r') as f: text=f.read() print text.split('\n') userinput=raw_input('myinput:') for i in text.split('\n'): if i in userinput: replace_str='*'*len(i.decode('utf-8')) word=userinput.replace(i,replace_str) return word print filterwords('filtered_words.txt')
再例如反黃系列:
開發(fā)敏感詞語過濾程序,提示用戶輸入評論內(nèi)容,如果用戶輸入的內(nèi)容中包含特殊的字符: 敏感詞列表 li = ["蒼老師","東京熱",”武藤蘭”,”波多野結(jié)衣”] 則將用戶輸入的內(nèi)容中的敏感詞匯替換成***,并添加到一個(gè)列表中;如果用戶輸入的內(nèi)容沒有敏感詞匯,則直接添加到上述的列表中。 content = input('請輸入你的內(nèi)容:') li = ["蒼老師","東京熱","武藤蘭","波多野結(jié)衣"] i = 0 while i < 4: for li[i] in content: li1 = content.replace('蒼老師','***') li2 = li1.replace('東京熱','***') li3 = li2.replace('武藤蘭','***') li4 = li3.replace('波多野結(jié)衣','***') else: pass i += 1
實(shí)戰(zhàn)案例:
一道bat面試題:快速替換10億條標(biāo)題中的5萬個(gè)敏感詞,有哪些解決思路?
有十億個(gè)標(biāo)題,存在一個(gè)文件中,一行一個(gè)標(biāo)題。有5萬個(gè)敏感詞,存在另一個(gè)文件。寫一個(gè)程序過濾掉所有標(biāo)題中的所有敏感詞,保存到另一個(gè)文件中。
1、DFA過濾敏感詞算法
在實(shí)現(xiàn)文字過濾的算法中,DFA是比較好的實(shí)現(xiàn)算法。DFA即Deterministic Finite Automaton,也就是確定有窮自動(dòng)機(jī)。
算法核心是建立了以敏感詞為基礎(chǔ)的許多敏感詞樹。
python 實(shí)現(xiàn)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="新疆騷亂蘋果新品發(fā)布會雞八" result = gfw.filter(text) print(text) print(result) time2 = time.time() print('總共耗時(shí):' + str(time2 - time1) + 's')
運(yùn)行效果:
新疆騷亂蘋果新品發(fā)布會雞八 ****蘋果新品發(fā)布會** 總共耗時(shí):0.0010344982147216797s
2、AC自動(dòng)機(jī)過濾敏感詞算法
AC自動(dòng)機(jī):一個(gè)常見的例子就是給出n個(gè)單詞,再給出一段包含m個(gè)字符的文章,讓你找出有多少個(gè)單詞在文章里出現(xiàn)過。
簡單地講,AC自動(dòng)機(jī)就是字典樹+kmp算法+失配指針
# -*- coding:utf-8 -*- import time time1=time.time() # AC自動(dòng)機(jī)算法 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() # 添加敏感詞函數(shù) 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 # 失敗指針函數(shù) 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]) # 查找敏感詞函數(shù) 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 # 加載敏感詞庫函數(shù) def parse(self, path): with open(path,encoding='utf-8') as f: for keyword in f: self.addword(str(keyword).strip()) # 敏感詞替換函數(shù) def words_replace(self, text): """ :param ah: AC自動(dòng)機(jī) :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="新疆騷亂蘋果新品發(fā)布會雞八" text2=ah.words_replace(text1) print(text1) print(text2) time2 = time.time() print('總共耗時(shí):' + str(time2 - time1) + 's')
運(yùn)行結(jié)果:
新疆騷亂蘋果新品發(fā)布會雞八 ****蘋果新品發(fā)布會** 總共耗時(shí):0.0010304450988769531s
以上就是python實(shí)現(xiàn)過濾敏感詞的詳細(xì)內(nèi)容,更多關(guān)于python 過濾敏感詞的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python實(shí)現(xiàn)的擬合二元一次函數(shù)功能示例【基于scipy模塊】
這篇文章主要介紹了Python實(shí)現(xiàn)的擬合二元一次函數(shù)功能,結(jié)合實(shí)例形式分析了Python基于scipy模塊進(jìn)行二元一次函數(shù)擬合相關(guān)科學(xué)運(yùn)算操作實(shí)現(xiàn)技巧,需要的朋友可以參考下2018-05-05Python函數(shù)式編程指南(二):從函數(shù)開始
這篇文章主要介紹了Python函數(shù)式編程指南(二):從函數(shù)開始,本文講解了定義一個(gè)函數(shù)、使用函數(shù)賦值、閉包、作為參數(shù)等內(nèi)容,需要的朋友可以參考下2015-06-06詳解Python手寫數(shù)字識別模型的構(gòu)建與使用
這篇文章主要為大家詳細(xì)介紹了Python中手寫數(shù)字識別模型的構(gòu)建與使用,文中的示例代碼簡潔易懂,對我們學(xué)習(xí)Python有一定的幫助,需要的可以參考一下2022-12-12Python實(shí)現(xiàn)GUI學(xué)生管理系統(tǒng)的示例代碼
這篇文章主要為大家介紹了如何留Python語言實(shí)現(xiàn)簡易的GUI學(xué)生管理系統(tǒng),文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)Python有一定幫助,需要的可以參考下2022-06-06python3第三方爬蟲庫BeautifulSoup4安裝教程
這篇文章主要為大家詳細(xì)介紹了python3第三方爬蟲庫BeautifulSoup4的安裝教程,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-06-06OpenCV+Python幾何變換的實(shí)現(xiàn)示例
這篇文章主要介紹了OpenCV+Python幾何變換的實(shí)現(xiàn)示例,圖像的幾何變換是指將一幅圖像映射到另一幅圖像內(nèi)。有縮放、翻轉(zhuǎn)、仿射變換、透視、重映射等操作。感興趣的可以了解一下2021-03-03Python中號稱神仙的六個(gè)內(nèi)置函數(shù)詳解
這篇文章主要介紹了Python中號稱神仙的六個(gè)內(nèi)置函數(shù),今天分享的這6個(gè)內(nèi)置函數(shù),在使用?Python?進(jìn)行數(shù)據(jù)分析或者其他復(fù)雜的自動(dòng)化任務(wù)時(shí)非常方便,需要的朋友可以參考下2022-05-05Python進(jìn)行數(shù)組的排序、倒序、截取方式
這篇文章主要介紹了Python進(jìn)行數(shù)組的排序、倒序、截取方式,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-02-02