To count words, split the text into words and keep a dictionary where each key is a word and each value is how many times you have seen it.
The program
python
text = "The cat sat on the mat. The cat was happy, and the mat was warm." counts = {} for word in text.lower().split(): word = word.strip(".,!?;:") counts[word] = counts.get(word, 0) + 1 for word, n in counts.items(): print(word, n)
output
the 4 cat 2 sat 1 on 1 mat 2 was 2 happy 1 and 1 warm 1
How it works
text.lower()makes "The" and "the" the same word. Without it, they would be counted separately.split()with no argument splits on any run of spaces, tabs or new lines.word.strip(".,!?;:")removes punctuation from both ends, so "mat." and "mat" are the same word.counts.get(word, 0)gives the current count, or 0 if the word is not in the dictionary yet. Then+ 1adds this occurrence.- A dictionary keeps keys in the order they were first added, so the words print in the order they first appear in the text.
Another way: Counter
collections.Counter does the counting for you, and most_common(n) gives the n most frequent words, largest count first:
python
from collections import Counter text = "The cat sat on the mat. The cat was happy, and the mat was warm." words = [w.strip(".,!?;:") for w in text.lower().split()] for word, n in Counter(words).most_common(3): print(word, n)
output
the 4 cat 2 mat 2
When two words have the same count, most_common() keeps them in the order they were first seen.