python敏感字替换_python用类实现文章敏感词的过滤方法示例
過濾一遍并將敏感詞替換之后剩余字符串中新組成了敏感詞語,這種情況就要用遞歸來解決,直到過濾替換之后的結果和過濾之前一樣時才算結束
第一步:建立一個敏感詞庫(.txt文本)
第二步:編寫代碼在文章中過濾敏感詞(遞歸實現)
# -*- coding: utf-8 -*-
# author 代序春秋
import os
import chardet
# 獲取文件目錄和絕對路徑
curr_dir = os.path.dirname(os.path.abspath(__file__))
# os.path.join()拼接路徑
sensitive_word_stock_path = os.path.join(curr_dir, 'sensitive_word_stock.txt')
# 獲取存放敏感字庫的路徑
# print(sensitive_word_stock_path)
class ArticleFilter(object):
# 實現文章敏感詞過濾
def filter_replace(self, string):
# string = string.decode("gbk")
# 存放敏感詞的列表
filtered_words = []
# 打開敏感詞庫讀取敏感字
with open(sensitive_word_stock_path) as filtered_words_txt:
lines = filtered_words_txt.readlines()
for line in lines:
# strip() 方法用于移除字符串頭尾指定的字符(默認為空格或換行符)或字符序列。
filtered_words.append(line.strip())
# 輸出過濾好之后的文章
print("過濾之后的文字:" + self.replace_words(filtered_words, string))
# 實現敏感詞的替換,替換為*
def replace_words(self, 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 self.replace_words(filtered_words, new_string)
def main():
while True:
string = input("請輸入一段文字:")
run = ArticleFilter()
run.filter_replace(string)
continue
if __name__ == '__main__':
main()
運行結果:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持我們。
時間: 2019-10-25
總結
以上是生活随笔為你收集整理的python敏感字替换_python用类实现文章敏感词的过滤方法示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 房子没有备案但交房了属于违约吗(房子没有
- 下一篇: python中运算符号怎样表示_Pyth