python用類實現(xiàn)文章敏感詞的過濾方法示例
更新時間:2019年10月27日 10:51:59 作者:代序春秋
這篇文章主要介紹了python用類實現(xiàn)文章敏感詞的過濾方法示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
過濾一遍并將敏感詞替換之后剩余字符串中新組成了敏感詞語,這種情況就要用遞歸來解決,直到過濾替換之后的結果和過濾之前一樣時才算結束
第一步:建立一個敏感詞庫(.txt文本)
第二步:編寫代碼在文章中過濾敏感詞(遞歸實現(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): # 實現(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() 方法用于移除字符串頭尾指定的字符(默認為空格或換行符)或字符序列。 filtered_words.append(line.strip()) # 輸出過濾好之后的文章 print("過濾之后的文字:" + self.replace_words(filtered_words, string)) # 實現(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)) # 當替換好的文章(字符串)與被替換的文章(字符串)相同時,結束遞歸,返回替換好的文章(字符串) if new_string == string: # 返回替換好的文章(字符串) return new_string # 如果不相同則繼續(xù)替換(遞歸函數(shù)自己調用自己) else: # 遞歸函數(shù)自己調用自己 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()
運行結果:
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
python Boltons庫實用功能探索(深度復制類型檢查重試機制)
這篇文章主要為大家介紹了python Boltons庫實用功能探索包含深度復制類型檢查重試機制及數(shù)據(jù)結構轉換實現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2024-01-01python使用for循環(huán)計算0-100的整數(shù)的和方法
今天小編就為大家分享一篇python使用for循環(huán)計算0-100的整數(shù)的和方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02Python?日期和時間處理教程之datetime?模塊的使用示例詳解
Python 中的日期不是獨立的數(shù)據(jù)類型,但我們可以導入一個名為 datetime 的模塊來使用日期作為日期對象,這篇文章主要介紹了Python?日期和時間處理教程:datetime?模塊的使用,需要的朋友可以參考下2023-10-10