Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Censoring a word in text but last word does not censor

Tags:

python

I am doing Python on Codecademy trying to censor out a word in a text. The code works but if the last word in the text has the word, it will not be censored.

I believe the for statement needs altering such as for x in (text + 1) but of course that causes an error. We are not to use built-in functions such as replace() Any ideas?

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"))

This returns [You ***** guy and ***** boy dirty.]

like image 414
Daniel Chang Avatar asked Jan 09 '17 10:01

Daniel Chang


People also ask

How do you write censored text?

One of the most common methods I work with for censoring text is using dashes to remove letters whenever possible. Instead of using several dashes, most people choose to use dashes or an em dash, which looks like “—”. In addition, they typically include only the first letter or the first and last letter of a word.


5 Answers

It's probably including the full stop in the last token, so it is comparing "dirty." with "dirty".

like image 61
Christopher Marshall Avatar answered Oct 22 '22 04:10

Christopher Marshall


The last occurrence of dirty is 'dirty.' instead of 'dirty'. It might be easier to use the replace function:

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

Without built-in functions:

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
like image 35
Maurice Meyer Avatar answered Oct 22 '22 02:10

Maurice Meyer


Christopher is correct that it's comparing dirty to dirty. with a period. As you said you cannot use replace function, so you could change your if statement to be

if x.startswith(word) == True:
like image 39
Christian Safka Avatar answered Oct 22 '22 02:10

Christian Safka


That's due to the last dirty having . so thus, there's difference between dirty and dirty(.). Here is a way to tackle the problem :

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"))

Output:

You ***** guy and ***** boy *****
like image 32
Taufiq Rahman Avatar answered Oct 22 '22 02:10

Taufiq Rahman


You can use re.sub to replace the work from text

import re
re.sub("word", "new_replaced_word", text)
like image 23
Aashutosh jha Avatar answered Oct 22 '22 04:10

Aashutosh jha