Text Filter - Python Programming Exercise

In this exercise, you will develop a Python program to create a utility that censors text files. This exercise is perfect for practicing file handling, string manipulation, and data processing in Python. By implementing this program, you will gain hands-on experience in handling file operations, string manipulation, and data processing in Python. This exercise not only reinforces your understanding of file handling but also helps you develop efficient coding practices for managing user interactions.

 Category

Managing Files

 Exercise

Text Filter

 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

 Copy 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

 More Python Programming Exercises of Managing Files

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  SQL to Plain Text

    In this exercise, you will develop a Python program to parse SQL INSERT commands and extract their data into separate lines of text. This exercise is perfect f...

  •  PGM Image Viewer

    In this exercise, you will develop a Python program to create a utility that reads and displays images in the PGM format, which is a version of the NetPBM image forma...

  •  Console BMP Viewer V2

    In this exercise, you will develop a Python program to create a utility that displays a 72x24 BMP file on the console. This exercise is perfect for practicing ...

  •  Saving Data to a Text File

    In this exercise, you will develop a Python program to collect multiple sentences from the user (continuing until the user presses Enter without typing anything) and ...

  •  Adding Content to a Text File

    In this exercise, you will develop a Python program that prompts the user to input multiple sentences, stopping when they press Enter without typing anything. This ...

  •  Show File Data

    In this exercise, you will develop a Python program to read and display the contents of a text file. This exercise is perfect for practicing file handling, com...