Write a Python program to count the occurrences of each word in a given sentence
In this exercise, you will learn how to count the occurrences of a particular word or each word in a text file. Generally, it is required in the development process to count the occurrence of each word or a particular word in a text document or a given sentence. Here, we have mentioned different ways to achieve this.
Count occurrences of each word in a given sentence using dictionary
In the given example, we first read the sentence from the user using a built-in function input() and store it in a variable, and then, we utilize a dictionary object that stores the word as the key and its count as the corresponding value. We loop through each word and count the occurrences of each word, adding them to the dictionary with count 1.
Output of the above code -
Pleae enter sentence: Python is a high level open source programming language. Python is an extremely powerful language. {'Python': 2, 'is': 2, 'a': 1, 'high': 1, 'level': 1, 'open': 1, 'source': 1, 'programming': 1, 'language.': 2, 'an': 1, 'extremely': 1, 'powerful': 1}Count occurrences of a word in a given file using count() function
In the above examples, we got the occurrence of each word, but what if we need to get the occurrence of a particular word in a file? Here is the simplest solution to this. We can use the count() function to count the occurrences of a particular word in a given file.
Suppose we have a text file 'demo.txt' that contains the following text-
Python is a high level open source programming language. Python is an extremely powerful language.Output of the above code -
need an explanation for this answer? contact us directly to get an explanation for this answerNumber of occurrences of the word : 2