Word Count Program in Python

This program counts the number of words in a given text. Below is the complete program along with a detailed explanation of its structure and functionality.

Program Explanation

The program is structured as follows:

  • Import necessary modules: We use the re module for regular expressions.
  • Define the function: A function named count_words is defined, which takes a string as input and returns the word count.
  • Use regular expressions to split the text: The function uses re.findall to find all words in the text. A word is defined as a sequence of alphanumeric characters.
  • Return the word count: The length of the list of words is returned as the word count.
  • Main block: The main block of the program takes input from the user and calls the count_words function to print the word count.

Python Program


import re

def count_words(text):
    """
    Counts the number of words in a given text.
    
    Args:
    text (str): The input text.
    
    Returns:
    int: The number of words in the text.
    """
    # Use regular expression to find all words
    words = re.findall(r'\b\w+\b', text)
    # Return the number of words
    return len(words)

if __name__ == "__main__":
    # Take input from the user
    text = input("Enter the text: ")
    # Call the count_words function
    word_count = count_words(text)
    # Print the word count
    print(f"The number of words in the given text is: {word_count}")

Function Documentation

count_words(text):

This function takes a string input text and returns the count of words in the text. Words are defined as sequences of alphanumeric characters, separated by non-alphanumeric characters.

  • Args: text (str) – The input text for which the word count is to be calculated.
  • Returns: int – The number of words in the text.

Example Usage

Here is an example of how the program works:


Enter the text: Hello, world! This is a test.
The number of words in the given text is: 6

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

Your email address will not be published. Required fields are marked *

error

Enjoy this blog? Please spread the word :)