Python每日练习之敏感词过滤器

题目传送口:https://github.com/Yixiaohan/show-me-the-code

第 0011 题: 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,否则打印出 Human Rights。

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

题目修改整合: 敏感词文本文件 filtered_words.txt,里面的内容为以下内容,当用户输入敏感词语时,则打印出 Freedom,然后使用星号*替换,直到替换替换全部敏感词,打印出 Human Rights。

北京
程序员
公务员
领导
牛比
牛逼
你娘
你妈
love
sex
jiangge

当用户输入「北京是个好城市,你娘的从程序员刻苦干活,现在当了领导,也变的厉害起来了。真的是很牛逼啊!」,则变成「*是个好城市,*的从*刻苦干活,现在当了*,也变的厉害起来了。真的是很*啊!」。

参考代码如下:

import re

def read_txt(file):                                   #打开敏感词文本并拿出敏感词
    with open(file) as f:
        data = f.read()
        list_data = data.split('\n')
        return list_data

def get_input():                                      #判断是否含有敏感词并替换
    input_word = input('please input:')
    for word in read_txt('filtered_words.txt'):
        if word in input_word:
            print('Freedom')
            p = re.sub(word,'*',input_word)
            print(p)
            input_word=p
            print(Change_input(input_word))
    return 'Human Rights'

def Change_input(str):                                #替换敏感词
    for word in read_txt('filtered_words.txt'):
        if word in str:
            p = re.sub(word,'*',str)
            return p

if __name__ == "__main__":
    print(get_input())

猜你喜欢

转载自www.cnblogs.com/one-two-one/p/12220666.html