Understanding AI · lesson 39 of 60 · about 6 minutes
Words That Go Together
Some words love to sit next to each other. Find the word pairs in a piece of text.
What you'll learn
- List every pair of neighbouring words
- Count which words follow a given word
- Explain why pairs help predict the next word
Neighbours
Peanut butter and... jelly? Fish and... chips? Words come in habits. After good, morning is likely; after once upon a, time is almost certain.
Looking at every pair of neighbouring words shows those habits. It's the seed of how a chatbot guesses what comes next.
Every pair of neighbours. `words[1:]` is the list without its first word, so `zip` lines each word up with the next.
words = "the cat sat on the mat".split()
for a, b in zip(words, words[1:]):
print(a, b)Output
the cat
cat sat
sat on
on the
the matTip
Look at what follows the: cat once, mat once. So after the, cat and mat are equally likely in this tiny text.
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.