Python program to count occurrences of a word in a string


In this tutorial, we are going to write a program that counts the number of times a word occurs in the string. You are given the word and a string, we have to calculate the frequency of the word in the string.

Suppose we have a string I am a programmer. I am a student. And the word is. The program that we are going to write will return a number 2 as the word occurs two times in the string.

Let's follow the below steps to achieve our goal.

Algorithm

1. Initialize the string and the word as two variables.
2. Split the string at spaces using the split() method. We will get a list of words.
3. Initialize a variable count to zero.
4. Iterate over the list.
4.1. Check whether the word in the list is equal to the given the word or not.
4.1.1. Increment the count if the two words are matched.
5. Print the count.

Try to write the code for the program on your own first. Let's see the code.

Example

## initializing the string and the word
string = "I am programmer. I am student."
word = "am"
## splitting the string at space
words = string.split()
## initializing count variable to 0
count = 0
## iterating over the list
for w in words:
   ## checking the match of the words
   if w == word:
      ## incrementint count on match
      count += 1
## printing the count
print(count)

Output

If you run the above program, you will get the following results.

2

Conclusion

If you have any doubts regarding the program, ask them in the comment section.

Updated on: 23-Oct-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements