Sub topic 2
Splitting Text into Tokens
This chapter assumes you know basic Python, can read a regular expression, and have seen fit and transform in scikit-learn. Tokenization is the first step in turning text into a document-term matrix. Every later count, weight and similarity score depends on the tokens you choose here.
What a token is
A token is the smallest unit of text that the model counts. In bag of words, a token is usually a word, but it can also be a number, a piece of punctuation, a word fragment or a single character. The tokenizer is the function that splits one string into a list of tokens.
Tokenization has no single correct answer. Is don't one token, two tokens, or don and t? Is e-mail one token or two? The answers change your vocabulary and so change your features. Choose rules that suit your task, and use the same rules for training and prediction.
Where tokenization sits in the pipeline
scikit-learn's vectorizers run a fixed sequence of steps on each document. You can replace or tune most of them.
The tokenizer runs after lowercasing. Stop word removal and n-grams work on the tokens it produces. If the tokenizer splits badly, those later steps cannot repair the result.
The default rule in scikit-learn
By default, CountVectorizer and TfidfVectorizer use this regular expression:
r"(?u)\b\w\w+\b"It finds runs of two or more word characters between word boundaries. Word characters are letters, digits and underscores, and (?u) makes this Unicode-aware. Three consequences follow:
- Single-character tokens such as
a,Ior5are dropped. - Punctuation is never part of a token, so
fine.becomesfine. - An apostrophe or hyphen ends a token, so
don'tyields onlydon.
Comparing tokenizers on one sentence
The code below calls build_analyzer(). It returns the function a vectorizer applies to each document: lowercasing, tokenizing, stop word removal and n-grams. With the default settings, you see the token list alone.
from sklearn.feature_extraction.text import CountVectorizer
text = "Don't panic! E-mail me at 9am, it's fine."
configs = {
"default": CountVectorizer(),
"keep single chars": CountVectorizer(token_pattern=r"(?u)\b\w+\b"),
"keep apostrophes and hyphens": CountVectorizer(
token_pattern=r"(?u)\b\w+(?:['-]\w+)*\b"
),
"whitespace split": CountVectorizer(tokenizer=str.split, token_pattern=None),
}
for name, vec in configs.items():
analyzer = vec.build_analyzer()
print(f"{name}: {analyzer(text)}")Running it prints:
default: ['don', 'panic', 'mail', 'me', 'at', '9am', 'it', 'fine']
keep single chars: ['don', 't', 'panic', 'e', 'mail', 'me', 'at', '9am', 'it', 's', 'fine']
keep apostrophes and hyphens: ["don't", 'panic', 'e-mail', 'me', 'at', '9am', "it's", 'fine']
whitespace split: ["don't", 'panic!', 'e-mail', 'me', 'at', '9am,', "it's", 'fine.']Compare the four lists:
- The default turns
Don'tinto the odd tokendonand loses theeofe-mail. - Keeping single characters recovers
e, but adds the noisy tokenstands. - The third pattern treats an apostrophe or hyphen between word characters as part of the word. This usually gives the most readable vocabulary for English.
- Whitespace splitting is simple, but it makes
panic!andpanicdifferent tokens, which fragments your counts.
Pattern design notes
A token pattern with capturing groups changes what findall returns, so use non-capturing groups (?: ... ).
When you pass your own tokenizer function, set token_pattern=None. Otherwise scikit-learn warns that the pattern is unused.
A custom tokenizer function
You can supply any function that maps a string to a list of strings. This example keeps URLs and hashtags as single tokens, which the default pattern would split apart.
import re
from sklearn.feature_extraction.text import CountVectorizer
TOKEN_RE = re.compile(r"https?://\S+|#\w+|\w+(?:['-]\w+)*")
def tokenize(text):
return TOKEN_RE.findall(text)
vec = CountVectorizer(tokenizer=tokenize, token_pattern=None, lowercase=True)
X = vec.fit_transform(["Loving #NLP! See https://example.com/nlp today."])
print(vec.get_feature_names_out())This prints ['#nlp' 'https://example.com/nlp' 'loving' 'see' 'today']. Lowercasing happens before the tokenizer is called, so the URL is also lowercased. That is harmless here but matters for case-sensitive identifiers. Set lowercase=False if case carries meaning.
Edge cases
The right choices depend on your data. These are the situations that most often cause trouble:
| Situation | What goes wrong | Typical remedy |
|---|---|---|
| Very short words such as `a`, `I`, `5` | The default pattern drops them | Use `\b\w+\b` if they carry signal (for example, `C`, `R`, version numbers) |
| Contractions and hyphens | Words split into fragments such as `don` | Allow `'` and `-` inside a word |
| Emoji and symbols | `\w` does not match them, so they vanish | Add them to the pattern, or use character n-grams |
| Languages without spaces (Chinese, Japanese) | Regex finds one huge token per phrase | Use a language-specific segmenter as `tokenizer` |
| Numbers, URLs, user IDs | Create huge numbers of rare tokens | Replace them with placeholders such as `NUM` before tokenizing |
| Misspellings and morphology | `run`, `running` and `runs` are distinct | Stemming or lemmatization in a custom tokenizer, or character n-grams |
Character-level analysis is another option. Setting analyzer="char_wb" splits text into character n-grams inside word boundaries. It handles typos and inflection without a dictionary, at the cost of a much larger vocabulary.
Common mistakes
- Changing the tokenizer between training and prediction. The vocabulary is built from training tokens. A different tokenizer at prediction time produces tokens the model never saw.
- Judging a tokenizer by eye on one sentence. Inspect
get_feature_names_out()on a real sample and look at the rare and strange tokens. - Using a slow tokenizer, such as a heavy NLP library, inside the vectorizer without thinking about corpus size. The tokenizer runs on every document, every time you fit or transform.
Exercise
What tokens does the default CountVectorizer produce for the text "A new X-ray, OK in 2024"? Assume lowercase=True.
Show answer
['new', 'ray', 'ok', 'in', '2024']. The default pattern needs two or more word characters, so "a" and "x" are dropped. The hyphen ends the token, which leaves "ray". "ok", "in" and "2024" each have at least two characters and are kept.
Exercise
You are classifying support tickets, and product names like "v2" and "C#" matter. Which part of the default tokenizer would hurt, and what is a first fix?
Show answer
The default pattern drops single-character tokens and ignores symbols such as "#". "v2" has two characters and survives, but "c#" becomes "c" and is then dropped. A first fix is tokenpattern=r"(?u)\b\w+\b" to keep single characters. For "c#" itself, write a pattern or custom tokenizer that allows the "#" character, then check getfeaturenamesout().