Open In App

Python program to count words in a sentence

Last Updated : 07 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will explore different methods for counting words in a sentence. The split() method is one of the simplest and most efficient ways to count words in a sentence.

Python
s = "Python is fun and versatile."

# Counting words
word_count = len(s.split())
print(word_count)

Output
5

Explanation:

  • The split() method divides the sentence into a list of words based on whitespace.
  • The len() function is used to calculate the total number of words in the list.

Let's explore some more methods and see the different python programs to count words in a sentence.

Using Regular Expressions

Regular expressions are particularly useful when the sentence contains special characters or multiple spaces.

Python
s = "Python: easy, powerful, and flexible!"

# Counting words using regex
import re
words = re.findall(r'\b\w+\b', s)

word_count = len(words)
print(word_count)

Output
Word Count: 5

Explanation:

  • The pattern \b\w+\b identifies whole words, considering word boundaries and alphanumeric characters.
  • The findall() function from the re module extracts all matching words into a list.
  • The len() function calculates the total number of words in the list.

Using collections.Counter

For additional analysis, such as word frequencies, the Counter class can be used.

Python
s = "Python is simple, yet powerful and simple."

# Counting words with Counter
from collections import Counter
word_list = s.split()
word_count = len(word_list)
word_frequencies = Counter(word_list)
print(word_count)
print(word_frequencies)

Output
7
Counter({'Python': 1, 'is': 1, 'simple,': 1, 'yet': 1, 'powerful': 1, 'and': 1, 'simple.': 1})

Explanation:

  • The split() method generates a list of words.
  • The len() function calculates the total number of words.
  • Counter provides a frequency count for each word in the list.

Using a loop

A manual approach using a loop provides more control over the word counting process.

Python
s = "Learning Python step by step."

# Counting words manually
word_count = 0
for word in s.split():
    word_count += 1
print("Word Count:", word_count)

Output
Word Count: 5

Explanation:

  • The split() method creates a list of words from the sentence.
  • A loop iterates through each word in the list, incrementing the count for every word.

Next Article
Practice Tags :

Similar Reads