python用類實(shí)現(xiàn)文章敏感詞的過濾方法示例
過濾一遍并將敏感詞替換之后剩余字符串中新組成了敏感詞語,這種情況就要用遞歸來解決,直到過濾替換之后的結(jié)果和過濾之前一樣時(shí)才算結(jié)束
第一步:建立一個(gè)敏感詞庫(kù)(.txt文本)

第二步:編寫代碼在文章中過濾敏感詞(遞歸實(shí)現(xiàn))
# -*- coding: utf-8 -*-
# author 代序春秋
import os
import chardet
# 獲取文件目錄和絕對(duì)路徑
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')
# 獲取存放敏感字庫(kù)的路徑
# print(sensitive_word_stock_path)
class ArticleFilter(object):
# 實(shí)現(xiàn)文章敏感詞過濾
def filter_replace(self, string):
# string = string.decode("gbk")
# 存放敏感詞的列表
filtered_words = []
# 打開敏感詞庫(kù)讀取敏感字
with open(sensitive_word_stock_path) as filtered_words_txt:
lines = filtered_words_txt.readlines()
for line in lines:
# strip() 方法用于移除字符串頭尾指定的字符(默認(rèn)為空格或換行符)或字符序列。
filtered_words.append(line.strip())
# 輸出過濾好之后的文章
print("過濾之后的文字:" + self.replace_words(filtered_words, string))
# 實(shí)現(xiàn)敏感詞的替換,替換為*
def replace_words(self, filtered_words, string):
# 保留新字符串
new_string = string
# 從列表中取出敏感詞
for words in filtered_words:
# 判斷敏感詞是否在文章中
if words in string:
# 如果在則用*替換(幾個(gè)字替換幾個(gè)*)
new_string = string.replace(words, "*" * len(words))
# 當(dāng)替換好的文章(字符串)與被替換的文章(字符串)相同時(shí),結(jié)束遞歸,返回替換好的文章(字符串)
if new_string == string:
# 返回替換好的文章(字符串)
return new_string
# 如果不相同則繼續(xù)替換(遞歸函數(shù)自己調(diào)用自己)
else:
# 遞歸函數(shù)自己調(diào)用自己
return self.replace_words(filtered_words, new_string)
def main():
while True:
string = input("請(qǐng)輸入一段文字:")
run = ArticleFilter()
run.filter_replace(string)
continue
if __name__ == '__main__':
main()
運(yùn)行結(jié)果:

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
python編程-將Python程序轉(zhuǎn)化為可執(zhí)行程序[整理]
python編程-將Python程序轉(zhuǎn)化為可執(zhí)行程序[整理]...2007-04-04
Python采集電影評(píng)論實(shí)戰(zhàn)示例
這篇文章主要為大家介紹了Python采集電影評(píng)論實(shí)現(xiàn)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04
python 將numpy維度不同的數(shù)組相加相乘操作
這篇文章主要介紹了python 將numpy維度不同的數(shù)組相加相乘操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2021-03-03
OpenCV利用python來實(shí)現(xiàn)圖像的直方圖均衡化
這篇文章主要介紹了OpenCV利用python來實(shí)現(xiàn)圖像的直方圖均衡化,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10

