簡體   English   中英

Python:用句子中的字符替換臟話

[英]Python: Replacing foul words with characters from a sentence

我正在嘗試將句子中的所有粗俗單詞替換為隨機字符。 我將在我的項目Mailing中使用它。 所以這是我到目前為止所做的。

curse=["apple","ball","car"]
fil = ["!","@","#","$","%","^","&","*","(",")"]
filword = ""
flag=0
word = raw_input(">>")
for each in curse:
    if each == word:
        worlen = len(word)
        flag=1
if flag==1:
    for c in fil:
        if len(filword) != worlen:
            filword+= c
word= word.replace(word, filword)
print word

假設列表詛咒中的那些單詞是骯臟的單詞。 我已經可以將其翻譯為隨機字符。 我的問題是如何替換句子中的臟話。 例:

>> Apple you, Ball that car

我希望我的輸出是這樣的:

!@#$% you, !@#$ that !@#

我怎樣才能做到這一點? 謝謝! :)

curse=["apple","ball","car"]
fil = ["!","@","#","$","%","^","&","*","(",")"]

word = raw_input(">>")
words = word.split();
for w  in words:
    p = w.lower()
    if p in curse:
        filword=""
        worlen = len(w);
        for i in range(worlen):
            filword += fil[j]
            j = (j + 1)%len(fil)
        word = word.replace(w,filword);

print word

我首先將行分成了一個單詞列表。 現在,對於單詞中的每個w,我都檢查了是否在詛咒列表中,如果是,我就做了一個單詞長度的假名。 j =(j +1)%len(fil)是因為worlen可能大於len(fil),在這種情況下,您將不得不重用字符。 然后終於取代了這個詞。

PS:此代碼在汽車,蘋果等情況下將失敗,因為它是基於“”拆分的。 在這種情況下,您可以刪除除“”以外的所有特殊字符,並將其存儲為另一個字符串作為預處理並對該字符串進行處理。

    import re
    word2 = re.sub(r'\w+', lambda x: x.group(0).lower() in curse and ''.join(fil[:len(c)]) or x.group(0), word)        
    print (word2)

    >>> '!@#$ you, !@#$ that !@#$'

如果您不關心每個字符都有自己唯一的過濾器替換,則可以使用random.sample從過濾器中選擇n個項,其中n是單詞的長度。 因此,考慮到這一點,您可以執行以下操作:

from random import sample

curse=["apple","ball","car"]
fil = ["!","@","#","$","%","^","&","*","(",")"]
s = "this apple is awesome like a ball car man"
ns = []

for w in s.split():
    ns.append(''.join(sample(fil, len(w)))) if w in curse else ns.append(w)
print(' '.join(ns))
# this ()*!^ is awesome like a %$^& @$^ man

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM