Count words with Counter

EasyCollections Programs · 1 of 20

Write a Python program to count the words in a sentence with Counter.

Advertisement
Output
[('to', 2), ('be', 2), ('or', 1)]

Approach

  1. Counter(text.split()).

Solution

Python
from collections import Counter text = "to be or not to be that is the question"counts = Counter(text.split())print(counts.most_common(3))
Output
[('to', 2), ('be', 2), ('or', 1)]
Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More collections programs

← All 20 Collections Programs