溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python實(shí)現(xiàn)敏感詞替換的方法

發(fā)布時(shí)間:2020-10-24 14:19:10 來(lái)源:億速云 閱讀:1359 作者:小新 欄目:編程語(yǔ)言

python實(shí)現(xiàn)敏感詞替換的方法?這個(gè)問(wèn)題可能是我們?nèi)粘W(xué)習(xí)或工作經(jīng)常見(jiàn)到的。希望通過(guò)這個(gè)問(wèn)題能讓你收獲頗深。下面是小編給大家?guī)?lái)的參考內(nèi)容,讓我們一起來(lái)看看吧!

python實(shí)現(xiàn)敏感詞替換的方法:首先倒入敏感詞文本;然后當(dāng)用戶輸入敏感詞匹配成功,則用【*】代替,代碼為【new_string = string.replace(words,"*"*len(words))】。

python實(shí)現(xiàn)敏感詞替換的方法:

思路

這道題練習(xí)的是字符串的替換,不過(guò)如果不小心的話很容易把過(guò)程想簡(jiǎn)單。在過(guò)程中會(huì)涉及到遞歸方法的使用,在Windows下用python2還涉及到編碼的轉(zhuǎn)換,要考慮到的是過(guò)濾完一遍字符串后可能并沒(méi)有過(guò)濾完的情況,例如在過(guò)濾一遍并將敏感字符串替換之后剩余字符串中新組成了敏感詞語(yǔ)的情況。這種情況就要用遞歸來(lái)解決,直到過(guò)濾替換完一遍之后的結(jié)果和過(guò)濾之前一樣沒(méi)有發(fā)生改變才能視為替換完成,否則在邏輯上是有疏漏的。

編寫腳本

代碼如下:

# -*- 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:"))

運(yùn)行測(cè)試結(jié)果:

python實(shí)現(xiàn)敏感詞替換的方法

感謝各位的閱讀!看完上述內(nèi)容,你們對(duì)python實(shí)現(xiàn)敏感詞替換的方法大概了解了嗎?希望文章內(nèi)容對(duì)大家有所幫助。如果想了解更多相關(guān)文章內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI