Python Practice › Collections Programs › Program 1
Count words with Counter
Write a Python program to count the words in a sentence with Counter.
Output
[('to', 2), ('be', 2), ('or', 1)]Approach
Counter(text.split()).
Solution
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)]Learn the concept
New to this topic? Read the lesson, then come back.