Python实现敏感词过滤替换

简介: [本文出自天外归云的博客园] 问题 最近在网上搜到了一些练习题,对第十二题稍作修改如下: 敏感词文本文件“filtered_words.txt”,里面的内容: 北京人 人大 北京 程序员 公务员 领导 牛比 牛逼 你娘 你妈 love sex jiangge 当用户输入敏感词语,则用星号“*”替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。

[本文出自天外归云的博客园]

问题

最近在网上搜到了一些练习题,对第十二题稍作修改如下:

敏感词文本文件“filtered_words.txt”,里面的内容:

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

当用户输入敏感词语,则用星号“*”替换,例如当用户输入「北京是个好城市」,则变成「**是个好城市」。

思路

这道题练习的是字符串的替换,不过如果不小心的话很容易把过程想简单。在过程中会涉及到递归方法的使用,在Windows下用python2还涉及到编码的转换,要考虑到的是过滤完一遍字符串后可能并没有过滤完的情况,例如在过滤一遍并将敏感字符串替换之后剩余字符串中新组成了敏感词语的情况。这种情况就要用递归来解决,直到过滤替换完一遍之后的结果和过滤之前一样没有发生改变才能视为替换完成,否则在逻辑上是有疏漏的。

编写脚本

代码如下:

# -*- coding: utf-8 -*-
import os
curr_dir = os.path.dirname(os.path.abspath(__file__))
filtered_words_txt_path = os.path.join(curr_dir,'filtered_words.txt')
import chardet

def filter_replace(string):
    string = string.decode("gbk")
    filtered_words = []
    with open(filtered_words_txt_path) as filtered_words_txt:
        lines = filtered_words_txt.readlines()
        for line in lines:
            filtered_words.append(line.strip().decode("gbk"))
    print replace(filtered_words, string)

def replace(filtered_words,string):
    new_string = string
    for words in filtered_words:
        if words in string:
            new_string = string.replace(words,"*"*len(words))
    if new_string == string:
        return new_string
    else:
        return replace(filtered_words,new_string)

if __name__ == '__main__':
    filter_replace(raw_input("Type:"))

运行测试结果:

 

 
相关文章
Python print() 打印两个 list ,实现中间换行
Python print() 打印两个 list ,实现中间换行
|
Python
Python实现因子分析(附案例实战)
Python实现因子分析(附案例实战)
1028 0
Python实现因子分析(附案例实战)
|
JSON 区块链 数据格式
Python实现一个简单的区块链
本文介绍如何用Python实现一个简单的区块链。
479 0
|
存储 数据安全/隐私保护 计算机视觉
python 实现pacs功能 推送下拉影像
python 实现dcmtk关联pacs功能 推送下拉影像
229 0
python 实现pacs功能 推送下拉影像
|
算法 大数据 Python
Leedcode 每日一练 搜索二维矩阵Ⅰ Python实现
Leedcode 每日一练 搜索二维矩阵Ⅰ Python实现
122 2
Leedcode 每日一练 搜索二维矩阵Ⅰ Python实现
|
前端开发 Python
Leecode加法题目3个 每日练习 Python实现
Leecode加法题目3个 每日练习 Python实现
87 0
Leecode加法题目3个 每日练习 Python实现
|
iOS开发 Python
Python实现微信消息连续发送
Python实现微信消息连续发送
Python实现微信消息连续发送
python实现微信小游戏“飞机大战”
python实现微信小游戏“飞机大战”
python实现微信小游戏“飞机大战”
|
Python
Python分分钟实现图书管理系统(含代码)
Python分分钟实现图书管理系统(含代码)
284 0
|
JSON 算法 数据安全/隐私保护
Python:使用PyJWT实现JSON Web Tokens加密解密
Python:使用PyJWT实现JSON Web Tokens加密解密
243 0