第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。
分析:正则匹配
代码如下:
#-*- coding: utf-8 -*-
import re
def check(input,filtered_words):
result=input
for i in filtered_words:
if i in result:
r=re.compile(i)
result=r.sub('*'*len(i.decode('utf-8')),result)
return result
return input
file = open('filtered_words.txt')
filtered_words=[line.replace('\n','') for line in file]
print check('lovely boy', filtered_words)
print check('程序员在上班。', filtered_words)
print check('我妈妈是农民。', filtered_words)
print check('北京欢迎你',filtered_words)
print check('hello python!',filtered_words)
结果如下:
****ly boy
***在上班。
我妈妈是农民。
**欢迎你
hello python!