Understanding AI · lesson 38 of 60 · about 6 minutes
Counting Words
The first thing a language AI can learn is which words are common. Count every word in a piece of text.
What you'll learn
- Count how often each word appears
- Find the most common word
- Explain why word counts tell AI something about language
Some words are everywhere
Count the words in any book and a few show up again and again: the, and, of, to. Other words appear once. Counting tells AI what's common and what's rare, and it's the first step towards knowing what's likely to come next.
Counting every word with a dictionary. `counts.get(w, 0)` gives the count so far, or 0 the first time.
words = "the cat sat on the mat".split()
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
print(counts)Output
{'the': 2, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1}Tip
In real text, the most common word is usually the in English.
Now try it yourself
This lesson is free in Codiqo, with 6 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.