Python練習題第 0012 題
https://github.com/Show-Me-the-Code/show-me-the-code
第0012題:敏感詞文本文件 filtered_words.txt,裏面的內容 和 0011題一樣,當用戶輸入敏感詞語,則用 星號替換,例如當用戶輸入【北京是個好城市】,則變成【**是個好城市】
敏感詞文件內容如下:
北京
程序員
公務員
領導
牛比
牛逼
你娘
你媽
love
sex
jiangge
可以只用str.replace,也可以用re.sub
Talk is cheap, show you my code.
#! /usr/bin/env python
#! -*- coding: utf-8 -*-
__author__ = 'Sophie'
import re
if __name__ == '__main__':
file = open("/Users/Sophie/PycharmProjects/Practice_0012/key_word.txt","r")
list_key_word =[]
try:
list_key_word = file.readlines()
finally:
file.close()
for i in range(len(list_key_word)):
list_key_word[i]=list_key_word[i].strip(" \n")
while(True):
userinput = raw_input("Please input something.\n")
result = ""
for x in list_key_word:
#result = userinput.replace(x,"*")
result = re.sub(x,"*",userinput)
userinput = result
print result
continue_or_not = raw_input("Do you want continue? Please input y/n. Any other inputs will be taken as y.\n")
if continue_or_not.lower() == 'n':
break