Objective
Develop a Python program to create a utility that censors text files. The program should read a text file and output its results to a new text file, replacing specified words with "[CENSORED]". The words to be censored will be stored in a separate data file, which is a text file containing one word per line.
Example Python Exercise
Show Python Code
# Python program to censor words in a text file
def load_censored_words(censor_file):
"""
Load the list of words to be censored from the specified file.
Each word is stored on a separate line.
"""
try:
with open(censor_file, 'r', encoding='utf-8') as file:
# Read lines, strip whitespace, and return as a set
return set(line.strip() for line in file if line.strip())
except FileNotFoundError:
print(f"Error: The censor file '{censor_file}' was not found.")
return set()
except Exception as e:
print(f"Error: {str(e)}")
return set()
def censor_text_file(input_file, output_file, censor_file):
"""
Censor specified words in the input file and write the results to the output file.
Replaces words found in the censor list with "[CENSORED]".
"""
# Load the list of words to be censored
censored_words = load_censored_words(censor_file)
if not censored_words:
print("No words to censor. Exiting.")
return
try:
# Open the input and output files
with open(input_file, 'r', encoding='utf-8') as infile, open(output_file, 'w', encoding='utf-8') as outfile:
for line in infile:
# Replace each censored word with "[CENSORED]"
for word in censored_words:
line = line.replace(word, "[CENSORED]")
# Write the censored line to the output file
outfile.write(line)
print(f"Censored text written to '{output_file}'.")
except FileNotFoundError:
print(f"Error: The input file '{input_file}' was not found.")
except Exception as e:
print(f"Error: {str(e)}")
# Example usage
if __name__ == "__main__":
# File paths
input_file = "example_text.txt" # The text file to censor
output_file = "censored_output.txt" # The file to save the censored text
censor_file = "censor_list.txt" # The file containing words to censor
censor_text_file(input_file, output_file, censor_file)
Output
censor_list.txt:
badword
offensive
secret
example_text.txt:
This is a secret message.
Do not use badword or any offensive language here.
Output (censored_output.txt):
This is a [CENSORED] message.
Do not use [CENSORED] or any [CENSORED] language here.
Share this Python Exercise