您好,登錄后才能下訂單哦!
python實(shí)現(xiàn)敏感詞替換的方法?這個(gè)問(wèn)題可能是我們?nèi)粘W(xué)習(xí)或工作經(jīng)常見(jiàn)到的。希望通過(guò)這個(gè)問(wèn)題能讓你收獲頗深。下面是小編給大家?guī)?lái)的參考內(nèi)容,讓我們一起來(lái)看看吧!
python實(shí)現(xiàn)敏感詞替換的方法:首先倒入敏感詞文本;然后當(dāng)用戶輸入敏感詞匹配成功,則用【*】代替,代碼為【new_string = string.replace(words,"*"*len(words))】。
python實(shí)現(xiàn)敏感詞替換的方法:
思路
這道題練習(xí)的是字符串的替換,不過(guò)如果不小心的話很容易把過(guò)程想簡(jiǎn)單。在過(guò)程中會(huì)涉及到遞歸方法的使用,在Windows下用python2還涉及到編碼的轉(zhuǎn)換,要考慮到的是過(guò)濾完一遍字符串后可能并沒(méi)有過(guò)濾完的情況,例如在過(guò)濾一遍并將敏感字符串替換之后剩余字符串中新組成了敏感詞語(yǔ)的情況。這種情況就要用遞歸來(lái)解決,直到過(guò)濾替換完一遍之后的結(jié)果和過(guò)濾之前一樣沒(méi)有發(fā)生改變才能視為替換完成,否則在邏輯上是有疏漏的。
編寫腳本
代碼如下:
# -*- coding: utf-8 -*- import os curr_dir = os.path.dirname(os.path.abspath(__file__)) filtered_words_txt_path = os.path.join(curr_dir,'filtered_words.txt') import chardet def filter_replace(string): string = string.decode("gbk") filtered_words = [] with open(filtered_words_txt_path) as filtered_words_txt: lines = filtered_words_txt.readlines() for line in lines: filtered_words.append(line.strip().decode("gbk")) print replace(filtered_words, string) def replace(filtered_words,string): new_string = string for words in filtered_words: if words in string: new_string = string.replace(words,"*"*len(words)) if new_string == string: return new_string else: return replace(filtered_words,new_string) if __name__ == '__main__': filter_replace(raw_input("Type:"))
運(yùn)行測(cè)試結(jié)果:
感謝各位的閱讀!看完上述內(nèi)容,你們對(duì)python實(shí)現(xiàn)敏感詞替換的方法大概了解了嗎?希望文章內(nèi)容對(duì)大家有所幫助。如果想了解更多相關(guān)文章內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。