敏感词文本文件 filtered_words.txt,当用户输入敏感词语,则用星号 * 替换,例如当用户输入“北京是个好城市”,则变成“**是个好城市”。
filtered_words.txt:
filtered_words.txt
#-*-coding: utf-8-*-
class Input(object):
def __init__(self):
self.filtered_words = list()
self.in_string = ''
self.out_string = ''
self.load_filtered_words()
def load_filtered_words(self, filename='filtered_words.txt'):
with open(filename, 'r') as file:
for line in file.readlines():
self.filtered_words.append(line.strip())
def filter_words(self):
self.out_string = self.in_string
for word in self.filtered_words:
if word in self.out_string:
self.out_string = self.out_string.replace(word, len(word)*'*'