題目要求以下:python
從文件解析敏感詞,從終端獲取用戶輸入。根據敏感詞對用戶輸入進行過濾。這裏過濾須要考慮不止一個過濾詞:即將讀取的全部過濾詞,放進一個列表,用屏蔽詞檢索用戶輸入,若是有屏蔽詞,則將其替換爲*,若是沒有,則不進行任何輸入。直到全部屏蔽詞遍歷完畢,則輸出過濾後字符串。app
過濾詞列表以下所示:code
具體實現步驟以下:blog
1. 從txt文件中讀取需求屏蔽的敏感詞列表ip
2. 從終端獲取用戶輸入,而後對輸入的語句與敏感詞列表進行匹配,若是匹配成功,則用‘*’替代字符串
代碼實現以下:input
import re def read_txt(file_name): # 讀取txt文件 with open(file_name, 'r') as file_to_read: lines = list() for line in file_to_read.readlines(): if line is not None: lines.append(line.strip('\n')) return lines def shield_sensitive_word(file_name): # 屏蔽敏感詞 sensitive_word = read_txt(file_name) text = input('請輸入:') for pattern in sensitive_word: match = re.search(pattern, text) if match is not None: text = text.replace(pattern, '*') print(text) if __name__ == "__main__": path = r"C:\Users\Administrator\Desktop\Python_Study\python_small_program\filtered_words.txt" shield_sensitive_word(path)