Counting Words with Python

Simple Python coding tutorial for beginners

Oliver Lövström
Internet of Technology
3 min readJan 30, 2024

--

In this article, we’re implementing a Python program for counting words in a text file — a great project for learning text analytics and data processing. It’s a perfect project for those starting their Python journey, focusing on essential concepts like file handling and string operations.

Photo by Brett Jordan on Unsplash

Implementing the Word Counter

Our first step is to create a count_words function. This function receives a file path and outputs the total word count within that file.

def count_words(file_path: str) -> int:
"""Count words in a file.

:param file_path: The path to the file to count words for.
:return: The number of words in the file.
"""
with open(file_path, "r") as file:
contents = file.read()
words = contents.split()
return len(words)
  • def count_words(file_path: str) -> int:: This line introduces our function count_words with one parameter, file_path.
  • Docstring: Provides a helpful description of the function’s purpose.
  • The function logic reads the file, splits the content into words, and counts them.

Testing the Function

Let’s put our function to the test with a text file:

word_count = count_words("example.txt")
print(f"The file contains {word_count} words.")

Execute this script with ‘example.txt’ to display the total word count:

$ python easy/word_counter.py example.txt 
The file contains 4 words.

Making It Interactive

Following our previous article, we’re making this script user-interactive using the argparse module. If you instead opt to use the input() function I highly recommend you check out this guide:

Setting Up argparse

Start by importing argparse:

import argparse

The Python Entry Point

Typical Python scripts have a starting point for execution:

if __name__ == "__main__":
# Our code goes here.

We configure argparse as follows:

if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Word Counter")

parser.add_argument("file_path", type=str, help="Path to the text file")
args = parser.parse_args()

main(args.file_path)

Here, we create an argparse object and define the expected argument, the file path.

Main Function

The main function will use the count_words function to count words in the specified file:

def main(file_path: str) -> None:
"""Word counter main function.

:param file_path: The path to the file to count words for.
"""
word_count = count_words(file_path)
print(f"The file contains {word_count} words.")

Full Implementation

"""Word counter."""
import argparse


def count_words(file_path: str) -> int:
"""Count words in a file.

:param file_path: The path to the file to count words for.
:return: The number of words in the file.
"""
with open(file_path, "r") as file:
contents = file.read()
words = contents.split()
return len(words)


def main(file_path: str) -> None:
"""Word counter main function.

:param file_path: The path to the file to count words for.
"""
word_count = count_words(file_path)
print(f"The file contains {word_count} words.")


if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Word Counter")

parser.add_argument("file_path", type=str, help="Path to the text file")
args = parser.parse_args()

main(args.file_path)

Running the Program

Execute the program using:

$ python word_counter.py "example.txt"
The file contains 4 words.

Challenge

Challenge yourself to extend this script to count characters in a file. We’ll provide a solution in our next article! You can find it here:

Further Reading

If you want to learn more about programming and, specifically, Python and Java, see the following course:

Note: If you use my links to order, I’ll get a small kickback. So, if you’re inclined to order anything, feel free to click above.

--

--