资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

python实现敏感词替换的方法

python实现敏感词替换的方法?这个问题可能是我们日常学习或工作经常见到的。希望通过这个问题能让你收获颇深。下面是小编给大家带来的参考内容,让我们一起来看看吧!

唐河ssl适用于网站、小程序/APP、API接口等需要进行数据传输应用场景,ssl证书未来市场广阔!成为创新互联的ssl证书销售渠道,可以享受市场价格4-6折优惠!如果有意向欢迎电话联系或者加微信:13518219792(备注:SSL证书合作)期待与您的合作!

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

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:"))

运行测试结果:

python实现敏感词替换的方法

感谢各位的阅读!看完上述内容,你们对python实现敏感词替换的方法大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注创新互联行业资讯频道。


当前题目:python实现敏感词替换的方法
标题网址:http://cdkjz.cn/article/pddjeh.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220