Sorry for getting stuck again, if your're up for helping, thanks!!! def censor(text, word): words = "" texts = "" for words in text: if words not in text: texts += words elif words in text: text += "****" return texts I edited to: def censor(text, word): words = "" texts = "" for words in text: if words not in text: texts += words elif words in text: text += "****" return texts
Here's a sample version of this I just rewrote:
def censor (remove, text): words = text.split(" ") new = "" for word in words: if (word==remove): for i in range(len(word)): new+="*" new+=" " else: new+=word+" " return new print(censor("panda", "My friends have a panda their panda is nice I like their panda very much."))
Let's go through it line by line...
Define the function with two parameters; what to censor, and what to censor from (the original text)
Define a words list as our original text, but split wherever there is a space, since we will ideally be working with a sentence.
Defining our new string. We will add onto this each time we check the words.
A for loop that iterates through each
Checking if the word that we're on is the same as the word we want to remove.
If number 5 is satisfied, we will loop however many letters the word has
We will add a star to represent each censored letter to our new string
We add a space, because we are finished with the word to be censored.
If number 5 is not satisfied...
We just add the same word to our new string, along with a space.
We now return the new string, so when our censor function is called, this will be its result.
A blank space to make the program pretty
We print out the result of the censor function, which we provide with two parameters. The word to remove, and the sentence to remove the word from.
Questions? Let me know.
Note: If you place the word to be censored at the end of a sentence with punctuation attached to it, it will not be found. There are ways to get past this error, but are not a part of this lesson. You can find a copy of code that does this here.
def censor(text, string): splittext=text.split() resultlist= for i in splittext: if i == string: resultlist.append("*" * len(string)) elif not i == string: resultlist.append(i) return " ".join(resultlist)
Thanks. I appreciate it. I am going to try these codes.
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.