假设有关键字存放在text.txt文件中,当用户输入文件中包含的敏感字时,则用星号*替换
例如:用户输入“西安我的故乡”时,则显示为“**我的故乡”
代码;
word_filter = set() #建立的是个集合,去除重复项
with open("test.txt","r") as f:
for w in f.readlines():
word_filter.add(w.strip())
print("文件中的关键字为:",word_filter) while True:
s = input("please enter your words:")
if s == "exit":
break
for w in word_filter:
if w in s:
s = s.replace(w,"*"*len(w))
print(s)
执行结果:
文件中的关键字为: {'北京', '上海', '西安'}
please enter your words:我爱这里
我爱这里
please enter your words:西安时我的故乡
**时我的故乡
please enter your words:exit