python show-me-the-code 第0012题

来源:互联网 发布:学闽南话的软件 编辑:程序博客网 时间:2024/04/28 07:26

第 0012 题: 敏感词文本文件 filtered_words.txt,里面的内容 和 0011题一样,当用户输入敏感词语,则用 星号 * 替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。

分析:正则匹配

代码如下:

#-*- coding: utf-8 -*-import redef check(input,filtered_words):result=inputfor i in filtered_words:if i in result:  r=re.compile(i)   result=r.sub('*'*len(i.decode('utf-8')),result)return resultreturn inputfile = 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!



0 0