2017-01-09 33 views
9

我正在做Codecademy上的Python,試圖檢查文本中的單詞。代碼的作品,但如果文本中的最後一個詞有這個詞,它不會被審查。Python:在文本中檢查一個單詞,但最後一個單詞不檢查

我認爲for聲明需要改變,如for x in (text + 1),但當然這會導致錯誤。我們不使用內置函數,如replace()有什麼想法?

def censor(text,word): 
    text = text.split() 
    for x in text: 
     if x == word: 
      text[text.index(x)] = "*" * len(word) 
    return " ".join(text) 

print(censor("You dirty guy and dirty boy dirty.", "dirty")) 

這將返回[You ***** guy and ***** boy dirty.]

+5

我建議你使用'海峽更換工作。替換'或're.sub' – Dmitry

+2

我同意你不能使用替換,但你可以使用拆分,索引,len,加入和打印。所有內置插件 – crowie

+1

你可以改變你的測試去除標點符號:'if x.translate(None,string.punctuation)== word:' – samgak

回答

17

它可能包括在最後一個記號的句號,所以它與"dirty"比較"dirty."

+6

你是否故意避免提出解決方案(因爲問題是在代碼學院)? – Darthfett

+0

是的,當人們指出我的答案但沒有完全回答時,我發現它更容易學習。 –

14

髒的最後一次發生是'dirty.'而不是'dirty'。 這可能是更容易使用的replace功能:

def censor(text,word): 
    return text.replace(word, len(word)*'*') 

沒有內置功能:

def censor(text,word): 
    while 1: 
     wordPosition = text.find(word) 
     if wordPosition < 0: 
      break 
     text = text[:wordPosition] + len(word)*'*' + text[wordPosition+len(word):] 
    return text 
+2

他確實提到「我們不使用內置函數,如replace()」。 –

+0

這是如何處理審查單詞可能是更大的單詞的一部分?例如,「屁股」只有當它看起來像一個單詞時纔會被審查,還是會被「刺客」審查? – Darthfett

+2

是的,現在它會審查'刺客' - 你應該實現一個查找功能來尋找真正的單詞...... –

1

這是最後一個髒有.所以由此因,有骯髒,骯髒(之間的差異。 )。這是解決這個問題的方式:

def censor(text, word): 
    wordlist = text.split() 
    new_words_list = [] 
    for item in wordlist: 
     if item.find(word) > -1: 
      new_words_list.append('*' * len(word)) 
     else: 
      new_words_list.append(item) 
    return " ".join(new_words_list) 

print(censor("You dirty guy and dirty boy dirty.", "dirty")) 

輸出:

You ***** guy and ***** boy ***** 
+3

你是否故意避免提出解決方案(因爲問題是在Code Academy的背景下)? – Darthfett

+0

@Darthfett是的。但我現在添加了代碼來解決問題。有人/ OP可能會發現它很有用。 – Inconnu

6

克里斯托弗是正確的,它是比較dirtydirty.一個時期。至於你說的,你不能使用replace功能,這樣你就可以改變你的if聲明是

if x.startswith(word) == True: 
+4

如果你將此延伸到褻瀆過濾器,那麼[Crapstone](https://en.wikipedia.org/wiki/Crapstone)的居民可能不會欣賞這種方法 – JonK

+0

只要'x.startswith(word):'請在Python if語句中不需要顯式比較「True」或「False」。 – zwol

1

您可以使用應用re.sub從文本

import re 
re.sub("word", "new_replaced_word", text) 
相關問題