python用類實(shí)現(xiàn)文章敏感詞的過濾方法示例
過濾一遍并將敏感詞替換之后剩余字符串中新組成了敏感詞語,這種情況就要用遞歸來解決,直到過濾替換之后的結(jié)果和過濾之前一樣時才算結(jié)束
第一步:建立一個敏感詞庫(.txt文本)
第二步:編寫代碼在文章中過濾敏感詞(遞歸實(shí)現(xiàn))
# -*- 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): # 實(shí)現(xiàn)文章敏感詞過濾 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() 方法用于移除字符串頭尾指定的字符(默認(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: # 如果在則用*替換(幾個字替換幾個*) new_string = string.replace(words, "*" * len(words)) # 當(dāng)替換好的文章(字符串)與被替換的文章(字符串)相同時,結(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("請輸入一段文字:") run = ArticleFilter() run.filter_replace(string) continue if __name__ == '__main__': main()
運(yùn)行結(jié)果:
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
對Matlab中共軛、轉(zhuǎn)置和共軛裝置的區(qū)別說明
這篇文章主要介紹了對Matlab中共軛、轉(zhuǎn)置和共軛裝置的區(qū)別說明,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-05-05Python實(shí)現(xiàn)自動發(fā)送郵件功能
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)自動發(fā)送郵件功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-12-12python Boltons庫實(shí)用功能探索(深度復(fù)制類型檢查重試機(jī)制)
這篇文章主要為大家介紹了python Boltons庫實(shí)用功能探索包含深度復(fù)制類型檢查重試機(jī)制及數(shù)據(jù)結(jié)構(gòu)轉(zhuǎn)換實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01python使用for循環(huán)計(jì)算0-100的整數(shù)的和方法
今天小編就為大家分享一篇python使用for循環(huán)計(jì)算0-100的整數(shù)的和方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02如何輕松實(shí)現(xiàn)Python數(shù)組降維?
歡迎來到Python數(shù)組降維實(shí)現(xiàn)方法的指南!這里,你將探索一種神秘又強(qiáng)大的編程技術(shù),想要提升你的Python編程技巧嗎?別猶豫,跟我一起深入探索吧!2024-01-01Python?日期和時間處理教程之datetime?模塊的使用示例詳解
Python 中的日期不是獨(dú)立的數(shù)據(jù)類型,但我們可以導(dǎo)入一個名為 datetime 的模塊來使用日期作為日期對象,這篇文章主要介紹了Python?日期和時間處理教程:datetime?模塊的使用,需要的朋友可以參考下2023-10-10