w3resource

Python: Count the occurrences of each word in a given sentence

Python String: Exercise-12 with Solution

Write a Python program to count the occurrences of each word in a given sentence.

Python String Exercises: Count the occurrences of each word in a given sentence

Sample Solution:-

Python Code:

def word_count(str):
    counts = dict()
    words = str.split()

    for word in words:
        if word in counts:
            counts[word] += 1
        else:
            counts[word] = 1

    return counts

print( word_count('the quick brown fox jumps over the lazy dog.'))

Sample Output:

{'the': 2, 'jumps': 1, 'brown': 1, 'lazy': 1, 'fox': 1, 'over': 1, 'quick': 1, 'dog.': 1} 

Flowchart:

Flowchart: Count the occurrences of each word in a given sentence

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to remove the characters which have odd index values of a given string.
Next: Write a Python script that takes input from the user and displays that input back in upper and lower cases.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Get Current Process Id:

import os
os.getpid()
21423

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook