Sub topic 2
Tokens and their attributes
This chapter explains how spaCy splits text into tokens and what each token carries. It assumes you can run Python, install packages with pip, and have installed en_core_web_sm with python -m spacy download en_core_web_sm. It also assumes you have seen nlp(text) return a Doc. Part-of-speech tags and dependency labels are covered in later chapters. Here you learn how to read the basic layer they sit on.
What a token is
A token is one unit of text that spaCy treats as a single piece: usually a word, a punctuation mark, or a number. A Token object does not hold its own copy of the data. It is a view onto a position in its parent Doc, which stores everything in compact arrays. Reading token.pos_ looks the value up in the Doc.
The tokenizer runs first and uses rules only. The components after it are statistical models, or rule-based components in the case of the lemmatizer. They add attributes to tokens that already exist. They do not change where tokens begin and end. The pipeline order shown is the usual one for en_core_web_sm, but the exact order depends on the model version. Check nlp.pipe_names if you need to be sure.
How the tokenizer decides
The tokenizer does not use a trained model. It works in three steps:
- Split the text on whitespace.
- For each chunk, check a table of special cases such as
don'torU.K.. If the chunk is in the table, use the stored split. - Otherwise, peel off prefixes (such as
$or an opening quote), suffixes (such as.or,), and infixes (such as a hyphen between letters), and repeat until nothing more can be split.
You can see this without loading a trained model, using a blank pipeline that contains only the tokenizer:
import spacy
nlp = spacy.blank("en")
doc = nlp("I don't think it's $5.")
print([t.text for t in doc])The result should be ['I', 'do', "n't", 'think', 'it', "'s", '$', '5', '.']. The special case turns don't into do and n't, which lets later components treat the negation as its own unit. The $ is a prefix and the final . is a suffix.
The tokenizer also follows one rule that makes it safe to use for offsets. It never loses characters. The pieces plus their trailing whitespace always rebuild the original string:
import spacy
nlp = spacy.blank("en")
text = "Hello world, it's fine."
doc = nlp(text)
assert "".join(t.text_with_ws for t in doc) == doc.text
assert doc.text == text
for t in doc:
assert text[t.idx : t.idx + len(t)] == t.text
print("round trip ok")Notice the repeated spaces in the input. spaCy keeps one space as whitespace_ on the previous token. Any extra spaces become their own tokens, and token.is_space is True for them. If your downstream code counts words, filter these out.
The attributes you will use most
The table groups the attributes that exist as soon as the tokenizer has run, plus the ones that need a trained component.
| Attribute | Type | Meaning | Needs a component? |
|---|---|---|---|
| `text` | str | The token as written | No |
| `whitespace_` | str | Trailing space, or empty string | No |
| `text_with_ws` | str | `text` plus `whitespace_` | No |
| `i` | int | Position in the `Doc` (token index) | No |
| `idx` | int | Character offset in the original text | No |
| `shape_` | str | Word shape, such as `Xxxx` or `dd` | No |
| `is_alpha`, `is_digit`, `is_punct`, `is_space` | bool | Character-class checks | No |
| `is_stop` | bool | In the language's stop word list | No |
| `like_num` | bool | Looks like a number, including `ten` | No |
| `lemma_` | str | Base form | Yes (lemmatizer) |
| `pos_`, `tag_` | str | Coarse and fine-grained tags | Yes (tagger or morphologizer) |
| `dep_`, `head` | str, Token | Dependency label and head token | Yes (parser) |
Print several of these at once to build a feel for them:
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("I don't think it's $5.")
print(f"{'i':<3}{'idx':<5}{'text':<8}{'alpha':<7}{'stop':<7}{'num':<6}{'shape'}")
for t in doc:
print(f"{t.i:<3}{t.idx:<5}{t.text:<8}{t.is_alpha!s:<7}{t.is_stop!s:<7}{t.like_num!s:<6}{t.shape_}")The is_ flags look only at the characters of a single token. They do not look at context. n't is not alphabetic because of the apostrophe, even though it is a word to a human reader. If you filter with is_alpha, you will drop n't and 's. This is a common source of lost negations. For a more careful filter, combine checks. For example, keep tokens where not t.is_punct and not t.is_space.
Strings and integers: the underscore convention
Many attributes come in two forms. token.pos_ is a string such as "VERB". token.pos is an integer. spaCy stores integer hashes internally because they are small and fast to compare, and it keeps a shared lookup table, the StringStore, to convert between the two.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Dogs bark.")
token = doc[1]
print(type(token.pos), type(token.pos_))
print(nlp.vocab.strings[token.pos] == token.pos_)In everyday code, use the underscore forms. They are readable and safe to compare with string literals. Use the integer forms only when you work with the low-level API, for example when building arrays with doc.to_array. A frequent bug is writing token.pos == "NOUN". It never matches, because pos is an integer.
Tokens, spans, and indexing
Indexing a Doc with an integer gives a Token. Slicing gives a Span, which is also a view and not a copy. Negative indexes work as in Python lists.
import spacy
nlp = spacy.blank("en")
doc = nlp("The quick brown fox jumps.")
print(doc[1].text) # a Token
print(doc[1:4].text) # a Span
print(doc[-1].text) # last token
print(doc[1:4].start, doc[1:4].end) # token indexes, end is exclusiveA Token does not compare equal to a plain string, so doc[0] == "The" is False. Compare doc[0].text == "The" instead. For case-insensitive checks use t.lower_.
Changing how text is split
Because tokenization is rule-based, you can change it without training anything. The simplest tool is a special case. The pieces you give must add up exactly to the original string.
import spacy
from spacy.symbols import ORTH
nlp = spacy.blank("en")
print([t.text for t in nlp("gimme that")])
nlp.tokenizer.add_special_case("gimme", [{ORTH: "gim"}, {ORTH: "me"}])
print([t.text for t in nlp("gimme that")])The first line prints ['gimme', 'that'] and the second prints ['gim', 'me', 'that']. Special cases apply to the whole whitespace-delimited chunk, so gimme, with a trailing comma still works. The tokenizer strips the comma first and then matches the rest.
Two cautions apply when you customize. The trained tagger and parser learned from text tokenized with the default rules, so unusual splits can lower their accuracy. Also, a special case can only split. It cannot merge two whitespace-separated words into one token. To merge words later, use doc.retokenize() after parsing.
Common errors
- Empty
pos_,tag_,dep_orlemma_. You usedspacy.blank("en")or disabled the component that fills the attribute. Checknlp.pipe_names. - Filtering with
is_alphaand losing contractions.n'tand'sare not alphabetic. Test what you actually want to remove. - Counting whitespace tokens as words. Repeated spaces, tabs and newlines produce tokens with
is_space == True. - Keeping tokens after discarding the
Doc. EveryTokenpoints into itsDoc, so storing tokens keeps the wholeDocin memory. Storetoken.textortoken.lemma_strings instead. - Comparing integer and string forms. Pair
poswith integers andpos_with strings. Never mix them.
Exercise
Using spacy.blank("en"), tokenize "Wait... it's 3 p.m.?" and print each token's text, whether is_punct is true, and its character offset idx. Then write one line of code that rebuilds the original text from the tokens. Which attribute makes the rebuild exact, and why can't you use " ".join(t.text for t in doc)?
Show answer
Code: import spacy; nlp = spacy.blank("en"); doc = nlp("Wait... it's 3 p.m.?"); for t in doc: print(t.text, t.ispunct, t.idx). Rebuild with "".join(t.textwithws for t in doc). The attribute textwithws is text plus whitespace, which records whether a space followed the token. Joining text with a space inserts spaces that were not in the original, for example between "it" and "'s" and before "?".
Exercise
A colleague writes [t for t in doc if t.pos == "NOUN"] and gets an empty list on a text that clearly contains nouns. What is wrong, and what is the fix? Name one other reason the list could be empty.
Show answer
t.pos is an integer hash, so it never equals the string "NOUN". Use t.pos == "NOUN". The list could also be empty if the Doc came from spacy.blank("en") or a pipeline where the tagger and morphologizer were disabled, since pos is then an empty string.