Count a specific word in a sentence with Python

Hello coders. Welcome back. In this post, we will learn to count a specific word in a sentence with Python. Counting the occurrence of a specific word in Python is very easy.

If you don’t know how to count the occurrence of a specific word in Python then stay with us we will guide you step by step. Although there are various approaches to perform this task. But in this post, we will learn some easy and decent method to count the word.

Also read: Count number of rows and columns in an excel file in Python

Let’s see the methods with the example given below.

Count occurrence of a specific word in a sentence in Python

To count a specific word in a sentence like counting “life”  in a sentence “The life of a student is like the life of a hermit”. In this sentence, the occurrence of “life” is 2 times. Let’s see the same example in the form of code.

str="The life of a student is like the life of a hermit"
count=str.count("life")
print(f"'Life' comes {count} time")

Output:

'Life' comes 2 times

But in some cases when the word we want to search or count is combined in another word then count () method also recognizes it and returns the number of its occurrence. To overcome this we will use the regex module in which we can define the start and end of the pattern.

Learn: Regular expression in python

See the example:

import re
string="Codespeedy Technology Pvt Ltd"
count = sum(1 for match in re.finditer(r"\bCode\b", string))
print(count)

Output:

0
Note: Install the regex module using the command “pip install regex”.

In code, we have used “\b” that bounds the checking of word with the start and endpoint. That means if the word “code” will be found separately only then it is counted.

That’s all for this post in which we learned to count a specific word in a sentence with Python. If you want to share anything related to this please comment below. If you have any doubts related to this post feel free to ask us. We will provide a solution to your problem soon.

Print colored text in the terminal in Python

Leave a Reply