假设有关键字存放在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

相关文章:

  • 2021-09-14
  • 2021-12-20
  • 2021-10-06
  • 2022-12-23
  • 2022-12-23
  • 2021-12-14
  • 2021-06-21
  • 2022-12-23
猜你喜欢
  • 2021-08-31
  • 2022-12-23
  • 2022-01-03
  • 2021-11-21
  • 2022-12-23
  • 2021-10-20
相关资源
相似解决方案