Home > other >  What if I wanted the user to type a phrase and it censors the "bad words" where would I ha
What if I wanted the user to type a phrase and it censors the "bad words" where would I ha

Time:01-29

def censor(text,word):
    t=str(text)
    w=str(word)
    if w in t:
        l=len(w)
        item = ("*" * l)
        return t.replace(w,item)
    else:
        return t
        
print(censor("salad","s"))

So instead of having two parameters, I would want a variable that asks the user for a sentence and then it checks if there are any curse words, if there isn't, it returns it unchanged

CodePudding user response:

It's a good idea to keep a useful function like 'censoring a text' in a function and user input and output separately, because the function could be easily reused in a situation where you don't want user interaction (like censoring another writting message for example).

It also helps to think ahead a little. Your example finds one word and blots it out, but do you need to censor multiple words? And what if the word is part of another word, is it still a bad word? ("My friend from Scherpenisse, has a massive collection of Dickensian fiction, but ever since they moved to Scunthorpe, they bedamn anything Shakespearean. Hey look, an American bushtit!")

Of course the problem is even harder with names to consider, just ask Dick Cheney and George Bush.

The easy things are quick to fix though:

def censor(text, forbidden):
    return ' '.join(
       word if word.casefold() not in forbidden else '*' * len(word)
    for word in text.split())

print(censor('I like fruit salad\n\nbecause it is fruitilicious', ['fruit', 'produce']))

Why this works:

  • ' '.join(<some iterable>) takes the elements from an iterable like a list and joins them together with the string at the start, a space in this case;
  • word.casefold() gives you the lowercase, simplified version of a word, to avoid things like aßhole or DaMn slipping through;
  • x if some_condition else y is an expression with a conditional built in;
  • '*' * len(word) - just a short version of what you already found.
  • word for word in text.split() gets you a generator that yield the words in text, split over whitespace, one at a time.

All of it taken together splits up text into words, checks if their simplified (casefolded) version is in the list of forbidden words and replaces them with a mask if so, otherwise, it just leaves the word - and at the end, it combines all of them back together into a sentence.

There are more problems to consider. For example, if you need to preserve the original formatting of a text (perhaps it contains multiple spaces, tabs, etc.) an approach using regular expressions might be better:

import re


def censor(text, forbidden):
    for word in forbidden:
        text = re.sub(rf'(?:(?<=^)|(?<=\s)){word}(?=$|\s)', '*' * len(word), text)
    return text


print(censor('I like fruit salad\n\nbecause it is fruitilicious', ['fruit', 'produce']))

This works mainly because of the regular expression, with these parts:

  • (?:(?<=^)|(?<=\s)) checks if the string has the start of a line ^ or whitespace \s immediately before it; it's done in two because the Python regex engine requires different options separated by | in a lookbehind to be of the same size;
  • {word} is replaced in the expression by each forbidden word, for each iteration, thanks to the f at the start of the string;
  • (?=$|\s) checks that the word is followed by the end of the line, or whitespace.
  • re.sub(some_regex, replacement, text) finds all occurrences of the given regular expression, and replaces them with replacement, which in this case is a string of the right number of *.

CodePudding user response:

def censor(text, words):
    for i in words:
        text = text.replace(i, len(i)*'*')
    return text


censor("You bloody idiot", ["bloody", "idiot"])

Output:
'You ****** *****'

CodePudding user response:

If you want to ask for user input on the command line in the function itself you can use input(). You can also just use input() outside of the function and pass that in.

def censor(text, word):
  if word in text:
    return text.replace(word, "*" * len(word))
  else:
    return text

sentence = input("Enter your sentence or enter to quit. ")
while sentence:
  censored_sentence = censor(sentence, "bad")
  print(censored_sentence)
  sentence = input("Enter your sentence or enter to quit. ")
  •  Tags:  
  • Related