日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python敏感字替换_python用类实现文章敏感词的过滤方法示例

發布時間:2023/12/3 python 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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用类实现文章敏感词的过滤方法示例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。