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

资源魔 58 0

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 python教程 python编程 python使用问题 敏感词替换

抱歉,评论功能暂时关闭!