AI Hints
Home›NLP Tutorial›Cleaning and Splitting Text
NLP · Lesson 5 of 106

Tokenisation

Splitting text into pieces.

⏱ 2 min read▶ Video at 9:16🎓 Free
Watch this lesson in the NLP courseWatch on YouTube ↗Full NLP course

How many words are in, can't? One, or two? What about New York? Or a price like twelve dollars fifty? Splitting text into pieces seems like the simplest thing in the world, until you try to do it properly.

Tokenisation
From the video: Tokenisation
  • How many words in can't?
  • New York? $12.50?
  • Harder than it looks

Why split is not enough

Python's split simply cuts at spaces. Look at the output. Dr dot keeps its dot, and order hash numbers stay stuck to their punctuation. SpaCy's tokeniser knows English. It keeps Dr dot together as one unit, splits can't into ca and n't, and separates the dollar sign. Run it, and compare the two. Each language has its own rules. Chinese has no spaces at all, for example.

tokens.pypython
import spacy

nlp = spacy.load("en_core_web_sm")
text = "Dr. Lee can't find order #48213! It cost $12.50, didn't it?"

print("Plain split:", text.split()[:7])
print("spaCy:      ", [t.text for t in nlp(text)][:12])
Output
Plain split: ['Dr.', 'Lee', "can't", 'find', 'order', '#48213!', 'It']
spaCy:       ['Dr.', 'Lee', 'ca', "n't", 'find', 'order', '#', '48213', '!', 'It', 'cost', '$']

Levels of tokens

We can split at many levels. Sentences, for summarising. Words, for classic methods. Characters, for spelling and tiny models. And word pieces, which are what transformers use. Remember that a model only ever sees numbers, one for each token. So how you split decides what the model can see. In our Deep Learning course, you built a word piece tokeniser from scratch.

Sentencesfor documents
Wordsfor classic methods
Characterstiny models
Word piecesfor transformers

Summary

Good tokenisation respects punctuation, prices, and contractions. Now we've got pieces. But, Running, running, and RUNNING are three separate things to a computer. Next, how to bring them together.

Key takeaways
  • split() is too simple
  • spaCy knows the rules
  • Models read tokens, as numbers
Next up: Normalising Text — treating the same thing as the same