Word Counter - Python Programming Exercise

In this exercise, you will develop a Python program to count the total number of words in a given text file. This exercise is perfect for practicing file handling, string manipulation, and loops in Python. By implementing this program, you will gain hands-on experience in handling file operations, string manipulation, and loops 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

Word Counter

 Objective

Develop a Python program to count the total number of words in a given text file. The program should read the file and compute the word count by splitting the contents based on spaces or punctuation.

 Example Python Exercise

 Copy Python Code
# This program reads a text file and counts the total number of words in the file.

import string

def count_words_in_file(filename):
    try:
        # Open the file in read mode
        with open(filename, 'r') as file:
            # Read the content of the file
            content = file.read()

        # Remove punctuation from the content
        content_without_punctuation = content.translate(str.maketrans('', '', string.punctuation))

        # Split the content into words based on spaces
        words = content_without_punctuation.split()

        # Count the number of words
        word_count = len(words)

        print(f"The total number of words in the file '{filename}' is: {word_count}")
    
    except FileNotFoundError:
        print(f"The file '{filename}' does not exist.")
    except Exception as e:
        print(f"An error occurred: {e}")

# Example usage
input_file = "example.txt"  # Replace with your input file name
count_words_in_file(input_file)

 Output

If the example.txt file contains:

Hello, this is an example text file. It has several words.

The output will be:

The total number of words in the file 'example.txt' is: 8

 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.

  •  BMP Dimensions with BinaryReader

    In this exercise, you will develop a Python program to read the dimensions (width and height) of a BMP file using a BinaryReader-like approach. This exercise i...

  •  Text to HTML Converter

    In this exercise, you will develop a Python program that functions as a "Text to HTML converter". This exercise is perfect for practicing file handling, string...

  •  Reverse Binary File V2

    In this exercise, you will develop a Python program to "reverse" a binary file using a "FileStream". This exercise is perfect for practicing file handling, byt...

  •  BMP Dimensions, Using FileStream

    In this exercise, you will develop a Python program to display the width and height of a BMP image file using a FileStream. This exercise is perfect for practi...

  •  File duplicator

    In this exercise, you will develop a Python program that duplicates a source file to a target file using FileStream and processes the file in 512 KB blocks. This e...

  •  MP3 file reader

    In this exercise, you will develop a Python program to read the ID3 tags from an MP3 file. This exercise is perfect for practicing file handling, byte manipula...