I’m working my way through the Censor Dispenser challenge project and have just completed step 4 (or so I thought). Here is my code so far:
def censor_one(email, phrase): return email.replace(phrase, '*' * len(phrase)) #print(censor_one(email_one, 'learning algorithms')) proprietary_terms = ["she", "personality matrix", "sense of self", "self-preservation", "learning algorithms", "her", "herself"] def censor_two(email, phrases): # Splits email using ' ' as the delimiter and replaces 'clean' words (with no punctuation) with '*'s equal to the word's length. This loop is designed to focus on phrases with no spaces in them. email_split = email.split(' ') for i in range(len(email_split)): if email_split[i].lower() in phrases: email_split[i] = '*' * len(email_split[i]) censored_email = ' '.join(email_split) # Iterates through each character in censored_email and looks for each phrase in a slice of censored_email equal to the phrase's length. If found, the slice has '*'s equal to the phrase's length assigned to it. This loop is designed to censor any phrases which weren't censored by the previous loop because of punctuation and/or spaces. for i in range(len(censored_email)): for phrase in phrases: if phrase == censored_email[i:i+len(phrase)].lower() and not censored_email[i-1].isalpha(): censored_email = censored_email.replace(censored_email[i:i+len(phrase)], '*' * len(phrase)) return censored_email #print(censor_two(email_two, proprietary_terms)) negative_words = ["concerned", "behind", "danger", "dangerous", "alarming", "alarmed", "out of control", "help", "unhappy", "bad", "upset", "awful", "broken", "damage", "damaging", "dismal", "distressed", "distressing", "concerning", "horrible", "horribly", "questionable"] def censor_three(email, phrases): censored_email = censor_two(email, proprietary_terms) count = 0 index = 0 for i in range(len(censored_email)): if count < 2: for phrase in phrases: if phrase == censored_email[i:i+len(phrase)].lower() and not censored_email[i-1].isalpha(): count += 1 index = i + len(phrase) else: break new_censored =  if count >= 2: new_censored.append(censored_email[:index]) new_censored.append(censor_two(censored_email[index:], phrases)) return ''.join(new_censored) #print(censor_three(email_three, negative_words)) print(censor_two(email_four, negative_words + proprietary_terms))
I tested my censor functions on email_four and did not get the output I was expecting. If you run the code, you’ll notice in the console that there are words which shouldn’t be censored - such as
I don’t understand why I’m getting this output in
email_four when, in
email_three, I get my expected output.
censor_two to censor every phrase found in a passed in list, and
censor_three to censor every phrase in
proprietary_terms as well as every phrase in
negative_terms after the second occurrence of a negative word – irrespective of case and punctuation.
These functions work as expected on
I welcome any help with this.