2017-01-09 34 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) 
相关问题