Count words in a sentence in Python program

PythonServer Side ProgrammingProgramming

In this article, we will learn about the solution to the problem statement given below.

Problem statement − We are given a string we need to count the number of words in the string

Approach 1: Using split() function

Split function breaks the string into a list iterable with space as a delimiter. if the split() function is used without specifying the delimiter space is allocated as a default delimiter.

Example

 Live Demo

test_string = "Tutorials point is a learning platform"
#original string
print ("The original string is : " + test_string)
# using split() function
res = len(test_string.split())
# total no of words
print ("The number of words in string are : " + str(res))

Output

The original string is : Tutorials point is a learning platform
The number of words in string are : 6

Approach 2: Using regex module

Here findall() function is used to count the number of words in the sentence available in a regex module.

Example

 Live Demo

import re
test_string = "Tutorials point is a learning platform"
# original string
print ("The original string is : " + test_string)
# using regex (findall()) function
res = len(re.findall(r'\w+', test_string))
# total no of words
print ("The number of words in string are : " + str(res))

Output

The original string is: Tutorials point is a learning platform The number of words in string is: 6

Approach 3: Using sum()+ strip()+ split() function

Here we first check all the words in the given sentence and add them using the sum() function.

Example

 Live Demo

import string
test_string = "Tutorials point is a learning platform"
# printing original string
print ("The original string is: " + test_string)
# using sum() + strip() + split() function
res = sum([i.strip(string.punctuation).isalpha() for i in
test_string.split()])
# no of words
print ("The number of words in string are : " + str(res))

Output

The original string is : Tutorials point is a learning platform
The number of words in string are : 6

All the variables are declared in the local scope and their references are seen in the figure above.

Conclusion

In this article, we have learned how to count the number of words in the sentence.

raja
Published on 23-Dec-2019 12:25:56
Advertisements