题目要求以下: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)