Introduction
In this article, we will discuss how to censor bad words from the given text. In some scenarios, we don’t want to show some bad words in the text and replace those words with any specific word like we skip some video clips with beep or silence. We will check the demonstration using Python scripting language.
Scenario
To demonstrate this, we will take input from user or Text: [Animals play an essential role in human life and specially on planet earth.] and a list of words [‘play’, ‘role’, ‘specially’] and a specific word [****] which will be replaced.
Code
# Write a default text
userText = "Animals play an essential role in human life and specially on planet earth."
OR
# Take input from user
userText = input("Enter Some Text to be Censored: ")
# Create an array of censored words
censors_words = ['play', 'role', 'specially']
# Define a specific word which will be replaced
repl_word = '****'
# Using join(), split() and array of words we will replace
result = ' '.join([repl_word if idx in censors_words else idx for idx in userText.split()])
# Actual user text
print("Actual String: " + str(userText))
# Text after replace censored words
print("Result: " + str(result))
Output
Actual String
Animals play an essential role in human life and specially on planet earth.
Result
Animals **** an essential **** in human life and **** on planet earth.
Summary
The purpose of this article is to demonstrate to beginners; how we can replace the censored words with a specific word using Python language. Happy Coding!! 😊