20170513 Python练习册0011替换敏感词

#!/usr/bin/env python
# -*-coding:utf-8-*-

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

def filted_word(filename):
word_list=[]#定义一个空列表
with open(filename,'r') as f:#以读打开文件
for line in f:#以行为单位遍历文件
content = re.sub(r' ','',line)#替换掉空格符
word_list.append(content.strip())#以行为单位添加进列表
print(word_list)
return word_list
def filer(input_word,f_file):
word_list = filted_word(f_file)
for f_word in word_list:#遍历敏感词列表中的每一个词
if f_word in input_word:#判断输入的文字里面是否在有敏感词
input_word = input_word.replace(f_word,'**')#有的话就将找到的敏感词替换为**
print(input_word)

add = 'F:\python\Python练习册\sensitivewords.txt'
name = input('请输入词语:')#输入word
if __name__=='__main__':
filer(name,add)
posted @ 2017-05-13 10:06  云ime  阅读(539)  评论(0编辑  收藏  举报