Profanity Filter Using Python

What is Profanity?

Profanity, also known as cursing, cussing, swearing, bad language, foul language, obscenities, expletives, or vulgarism, is a socially offensive use of language.

Now here we will use the better_profanity library of python to check whether our sentence contains profane(abusive) words or not

Let’s use it…

Installation

Firstly we have to install the library with following command

$ pip install better_profanity

Note
This package works with Python 3.4+ and PyPy3.

from better_profanity import profanity    #import better_profanity module
text = "Hello,how are you?"               #Enter text to check
if(profanity.contains_profanity(text)):   #to check if the input text has any swear words.
    print("The text contains profane words")
else:
    print("No text does not contain profane words")

Here, ‘contains_profanity’ method will check for profane words in text and return True if input text has any bad or abusive word else false.

Profanity Filter using Python

Example 2

text = "What the shit are you doing?" 

Profanity Filter using Python

Here "Shit " is considered a profane word.

Alternatively, we can also Censor(detect) swear words from a text using censor method.

from better_profanity import profanity #import better_profanity module
text = "What the shit are you doing?" #Enter text to check
#Do censoring
censored_text = profanity.censor(text) #censor text
print(censored_text)

Profanity Filter using Python

Note
By default, profanity replaces each swear words with 4 asterisks ****.

But we can replace the swear text by any character Except for @, $, *, ", '. using the below syntax.

censored_text = profanity.censor(text,'^^')

Here The shit is replaced with ^^^^ character.

Conclusion

In this article, we learned how to use the better profanity library to check profanity in text. The difference between contains_profanity and censor method is that the former returns output as True or False while the censor method replaces the profane word with special characters.

Thank You


Similar Articles