How to Count the Number of Times a Word Occurs in a Text in Python



Python


In this article, we show how to count the number of times a word occurs in a text in Python.

In the following link shown, we show how to do this using regular expressions.

However, in this article, we take a more basic approach. We simply create a custom function.

Many people find regular expressions to be intimidating, so this is a much more direct approach to building a word finder, such as what you see in text editors such as notepad or Microsoft Word.

So in the code below, we write a custom function that can check how many times a word appears in a text.



So the first thing we have in our code is a string, string1.

You see how we have the word 'beach' 3 times in our string.

We then split the sentence using the Python split() function so that we can examine each word of the string (of the text).

We then have a list, list1, and set it equal to an empty list.

We then have a for loop that loops through each word of the split string.

If the word is equal to 'beach', then we append this word to the list, list1, with the append() function.

We then create another variable, lengthstring, that gets the length of the list. This allows us to know how many times the word 'beach' appeared in the string.

We then print out the number of times the word beach occurs in the string.

Since 'beach' appears 3 times in the string, we get the word occurrence of 'beach' 3 times.

And this is how we can count the number of times a word occurs in a text in Python.


Related Resources

How to Randomly Select From or Shuffle a List in Python



HTML Comment Box is loading comments...