敏感词文本文件 filtered_words.txt,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。
input_words = input('请输入对话:')
with open('../data/filtered_words.txt', encoding='utf-8') as f:
text_list = f.readlines()
text_list = [x.strip() for x in text_list]
for i in range(len(input_words)):
for j in range(len(text_list)):
word = input_words[i]
if word == text_list[j][0]:
len_j = len(text_list[j])
if input_words[i:i + len_j] == text_list[j]:
input_words = input_words.replace(input_words[i:i + len_j], '*' * len_j)
print(input_words)