Cencor exercise in python


#1



Censor

I cannot see how my code is wrong?

Can anyone help?


def censor(text, word):
    hash_tag = ""
    for char in word:
        if char in word:
            hash_tag += "*"
    print hash_tag
        
    censor_list = text.split(" ")
    for list_word in censor_list:
        if list_word == word.lower():
            censor_list = " ".join(censor_list)
            censor_list = censor_list.replace(list_word, hash_tag)
            
    print censor_list
    return censor_list
    
    


censor("hey hey hey","hey")


#2

What is the objective of the first part?

To produce a string of asterisks? That's a lot of logic from such a simple task.

aster = len(word) * "*"

The above line makes no sense to me placed where it is.

The above line is attempting to mutate the list currently being iterated. Nothing will happen.

This code needs a rethink, sorry to say.

Consider string.replace(). This method is greedy if not given a limit, meaning it does a global replace of all instances of the target substring. If you wish to use it there is no need for a loop at all.

text.replace(word, aster);

Does take the fun out of it, though. Give your loop a good look.There is a way that one can iterate over the list and swap items but it requires an index so a range() is needed. As we've already determined, we cannot alter data in a lookup loop, only an indexed loop.

    for x in range(len(sequence)):
        if sequence[x] == word:
            sequence[x] = aster
    return " ".join(sequence)

#3

Supplement

I did earlier say that string.replace() took all the fun out, which in the case of seeking an algorithm, it does but that is not entirely the case. We can have fun with it, but in a different approach that veers away to anonymous procedure

>>> censor = lambda x, w: x.replace(w, len(w) * '*')
>>> censor("hey hey hey", "hey")
'*** *** ***'
>>>

Now we can re-use this expression to censor a list of words from a block of text.

def censored(x, s):
    for h in s:
        x = censor(x,h)
    return x

print (censored("hey you, get off the nice grass",['you','nice']))

# hey ***, get off the **** grass

With a minor tweak we can use this function for all instances, list or word. We'll straighten out the dependency issue as well.

def censor(x, s):
    swap = lambda x, w: x.replace(w, len(w) * '*')
    for w in list(s):
        x = swap(x, w)
    return x

It is clear that this exercise is gearing us up for bigger challenges and also opening some doors. Worth the time spent.


#4

Wow mtf, thanks for the bashing !!!
I get your point now about str.replace(), using index loop and my over complex aster logic.
Thanks a lot lesson noted.
Your tips are invaluable and they clarified a lot for me.