Python中实现敏感词替换的思路和方法是什么?
导读:这篇文章给大家分享的是Python中实现敏感词替换的思路和方法。小编觉得挺实用的,因此分享给大家做个参考,文中的示例代码介绍得很详细,有需要的朋友可以参考,接下来就跟随小编一起了解看看吧。 python实现敏感词替换的方法:思路这道题练习的...
这篇文章给大家分享的是Python中实现敏感词替换的思路和方法。小编觉得挺实用的,因此分享给大家做个参考,文中的示例代码介绍得很详细,有需要的朋友可以参考,接下来就跟随小编一起了解看看吧。
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有帮助,想要了解更多可以继续浏览网络其他相关的文章。
文本转载自PHP中文网
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: Python中实现敏感词替换的思路和方法是什么?
本文地址: https://pptw.com/jishu/651007.html
