2016-03-15 58 views
1

我試圖用一個句子中的所有犯規詞替換成隨機字符。我將把它用於我的項目郵件。所以這就是我迄今所做的。Python:用一個句子中的字符替換犯規詞

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 

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

[email protected]#$% you, [email protected]#$ that [email protected]# 

我怎麼能這樣做?謝謝! :)

+2

大多數基本答案是使用'.split()'你的字符串,你的邏輯分別適用於每個字,然後加入'()'一切以句子 – Idos

回答

1
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 

我第一次把這條線分成一個名爲單詞的列表。現在對於每一個字,我檢查了是否在詛咒列表中,如果是的話,我已經寫了一個長度單詞。 j =(j + 1)%len(fil)是因爲worlen可能比len(fil)大,在這種情況下,你將不得不重用這些字符。 然後最後換掉了這個詞。

PS:此代碼將失敗的案件,如汽車,蘋果,因爲它分裂的基礎上「」。在這種情況下,您可以刪除除「」之外的所有特殊字符,並將其另存爲另一個字符串作爲預處理並處理該字符串。

+0

它的工作原理!非常感謝你:) – eshi

+0

沒問題! :) 樂於幫助! :) –

0

如果你不關心有自己獨特的過濾器更換每一個字符,你可以使用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 
相關問題