[本文出自天外歸雲的博客園]
問題
最近在網上搜到了一些練習題,對第十二題稍作修改如下:
敏感詞文本文件“filtered_words.txt”,里面的內容:
北京人
人大
北京
程序員
公務員
領導
牛比
牛逼
你娘
你媽
love
sex
jiangge
當用戶輸入敏感詞語,則用星號“*”替換,例如當用戶輸入「北京是個好城市」,則變成「**是個好城市」。
思路
這道題練習的是字符串的替換,不過如果不小心的話很容易把過程想簡單。在過程中會涉及到遞歸方法的使用,在Windows下用python2還涉及到編碼的轉換,要考慮到的是過濾完一遍字符串后可能並沒有過濾完的情況,例如在過濾一遍並將敏感字符串替換之后剩余字符串中新組成了敏感詞語的情況。這種情況就要用遞歸來解決,直到過濾替換完一遍之后的結果和過濾之前一樣沒有發生改變才能視為替換完成,否則在邏輯上是有疏漏的。
編寫腳本
代碼如下:
# -*- 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:"))
運行測試結果: