In this post, we will see how to count the occurrences of each word in a given string sentence.
Step 1: Declare a String and store it in a variable.
Step 2: Declare a variable wordCount and initialise it to 0.
Step 3: Split the string using split(“ ”) function with space as the parameter and store all the words in a list.
Step 4: Use a for loop to iterate over the words in the list. While iterating check if the word in the list matches the word given by the user and if match found then increment the value of wordCount variable by 1.
Step 5: After completing the for loop print the value of wordCount variable.
Step 6: End.
Input: "This is a sample Python program, Welcome to World Of Python Programming!" Output: Number of occurrences found in the string: 2
string="This is a sample Python program, Welcome to World Of Python Programming!" word="Python" list= wordCount=0 list=string.split(" ") for i in range(0,len(list)): if(word==list[i]): wordCount=wordCount+1 print("Number of occurrences found in the string:") print(wordCount)
Number of occurrences found in the string: 2