python教程:python如何实现敏感词替换

 所属分类:php教程

 浏览:304次-  评论: 0次-  更新时间:2022-09-29
描述:更多教程资料进入php教程获得。 python实现敏感词替换的方法:首先倒入敏感词文本;然后当用户输入敏感词匹配成功,则用【*】代替,代码为...
更多教程资料进入php教程获得。

python实现敏感词替换的方法:首先倒入敏感词文本;然后当用户输入敏感词匹配成功,则用【*】代替,代码为【new_string = string.replace(words,"*"*len(words))】。

程序员必备接口测试调试工具:立即使用
Apipost = Postman + Swagger + Mock + Jmeter
Api设计、调试、文档、自动化测试工具
后端、前端、测试,同时在线协作,内容实时同步

python实现敏感词替换的方法:

思路

这道题练习的是字符串的替换,不过如果不小心的话很容易把过程想简单。在过程中会涉及到递归方法的使用,在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:"))

运行测试结果:

6b587d7eeddf78176c44c7ed75248e2.png

相关免费学习推荐:python教程(视频)

以上就是python如何实现敏感词替换的详细内容,更多请关注zzsucai.com其它相关文章!

积分说明:注册即送10金币,每日签到可获得更多金币,成为VIP会员可免金币下载! 充值积分充值会员更多说明»

讨论这个素材(0)回答他人问题或分享使用心得奖励金币

〒_〒 居然一个评论都没有……

表情  文明上网,理性发言!