Loading lessons...
Project 5: Word Counter
Project 5: Word Counter
Count how many times each word appears in a sentence using a dictionary.
The goal
Read a sentence, split it into words, and print each word with its count, most common first.
What you practice
- Dictionaries
split()- Loops
sorted()with a key
Starter code
sentence = input("Type a sentence: ")
words = sentence.lower().split()
print(words)
Step-by-step
- Build a dict:
counts = {}. - Loop over
words; add 1 tocounts[word], starting at 0 if new. - Print each word and count.
- Sort the results:
sorted(counts, key=counts.get, reverse=True). - Handle an empty input gracefully.
Checklist
- [ ] The sentence is split into words
- [ ] Every word is counted
- [ ] Lowercase normalizes the text
- [ ] Results sort by count
- [ ] Empty input doesn't crash
TL;DR
split()breaks text into words.- A dict maps each word to its count.
counts[word] = counts.get(word, 0) + 1counts cleanly.