How do you count the occurrences of a word in a string in Python?

This is a Python Program to count the occurrences of each word in a given string sentence.Problem DescriptionThe program takes a string and counts the occurrence of each word in th

How do you count the occurrences of a word in a string in Python?

This is a Python Program to count the occurrences of each word in a given string sentence.Problem Description

The program takes a string and counts the occurrence of each word in the given sentence.Problem Solution

1. Take a string and a word from the user and store it in separate variables.
2. Initialize a count variable to 0.
3. Split the string using space as the reference and store the words in a list.
4. Use a for loop to traverse through the words in the list and use an if statement to check if the word in the list matches the word given by the user and increment the count.
5. Print the total count of the variable.
6. Exit.advertisementProgram/Source Code

Here is source code of the Python Program to calculate the length of a string without using library functions. The program output is also shown below.string=raw_input("Enter string:")word=raw_input("Enter word:")a=[]count=0a=string.split(" ")for i in range(0,len(a)): if(word==a[i]): count=count+1print("Count of the word is:")print(count)Program Explanation

1. User must enter a string and a word and store it in separate variables.
2. The count variable is initialized to zero.
3. The string is split into words using space as the reference and stored in a list.
4. The for loop is used to traverse through the words in the list.
5. The count is incremented each time the word in the list is equal to the word given by the user.
6. The total count of the word is printed.Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!advertisementadvertisementRuntime Test CasesCase 1: Enter string:hello world Enter word:hello Count of the word is: 1 Case 2: Enter string:orange blue red orange Enter word:orange Count of the word is: 2

Sanfoundry Global Education & Learning Series  Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.Check this: Programming MCQs | Information Technology Booksadvertisement« Prev - Python Program to Create a New String Made up of First and Last 2 Characters» Next - Python Program to Add a Key-Value Pair to the DictionaryNext Steps:

  • Get Free Certificate of Merit in Python Programming
  • Participate in Python Programming Certification Contest
  • Become a Top Ranker in Python Programming
  • Take Python Programming Tests
  • Chapterwise Practice Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
  • Chapterwise Mock Tests: Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10Related Posts:

  • Apply for Programming Internship
  • Apply for Python Internship
  • Buy Information Technology Books
  • Practice Programming MCQs
  • Buy Python Books

Video liên quan