首頁  >  文章  >  後端開發  >  python如何實現敏感詞替換

python如何實現敏感詞替換

coldplay.xixi
coldplay.xixi原創
2020-10-23 14:38:4317910瀏覽

python實作敏感詞替換的方法:先倒入敏感字文字;然後當使用者輸入敏感字詞匹配成功,則用【*】代替,程式碼為【new_string = string.replace(words,"* "*len(words))】。

python如何實現敏感詞替換

python實作敏感詞替換的方法:

##想法

這題練習的是字串的替換,不過如果不小心的話很容易把過程想簡單。在過程中會涉及到遞歸方法的使用,在Windows下用python2還涉及到編碼的轉換,要考慮到的是過濾完一遍字符串後可能並沒有過濾完的情況,例如在過濾一遍並將敏感字符串替換之後剩餘字串中新組成了敏感詞語的情況。這種情況就要用遞歸來解決,直到過濾替換完一遍之後的結果和過濾之前一樣沒有發生改變才能視為替換完成,否則在邏輯上是有疏漏的。

編寫腳本

程式碼如下:

# -*- coding: utf-8 -*-
import os
curr_dir = os.path.dirname(os.path.abspath(__file__))
filtered_words_txt_path = os.path.join(curr_dir,'filtered_words.txt')
import chardet
def filter_replace(string):
    string = string.decode("gbk")
    filtered_words = []
    with open(filtered_words_txt_path) as filtered_words_txt:
        lines = filtered_words_txt.readlines()
        for line in lines:
            filtered_words.append(line.strip().decode("gbk"))
    print replace(filtered_words, string)
def replace(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 replace(filtered_words,new_string)
if __name__ == '__main__':
    filter_replace(raw_input("Type:"))

執行測試結果:

python如何實現敏感詞替換

##相關免費學習推薦:

python教學(影片)

以上是python如何實現敏感詞替換的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn