Python Program to Count Words in Text

 

 

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

 

Leave a Reply

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