Sub topic 9
Walking the tree: children, subtree, ancestors
The previous chapters gave every token a dep_ label and a head. This chapter uses those two attributes to move around the parse. You will go down from a head to its dependents, up from a dependent to the root, and across to a whole phrase.
This chapter assumes you can run Python with en_core_web_sm installed. It also assumes you know what token.dep_ and token.head mean and that you know basic grammar terms such as subject, object, and modifier.
The tree behind the attributes
A spaCy parse is a tree with one root per sentence. Each token has exactly one head, except the root, whose head is itself. The relation is stored in one direction, token to head. spaCy also provides the reverse view, head to dependents, so you can walk in either direction.
The final period also attaches to jumps as punct. It is left out of the diagram to keep it readable.
The navigation attributes
| Attribute | Direction | What it returns |
|---|---|---|
| `token.head` | up one step | The single parent token |
| `token.children` | down one step | An iterator over direct dependents, in sentence order |
| `token.lefts` | down one step | Direct dependents that appear before the token |
| `token.rights` | down one step | Direct dependents that appear after the token |
| `token.n_lefts`, `token.n_rights` | down one step | Counts of left and right dependents |
| `token.subtree` | down, all levels | The token, its dependents, their dependents, and so on, in sentence order |
| `token.ancestors` | up, all levels | The head, the head's head, and so on, up to the root |
| `token.left_edge`, `token.right_edge` | down, all levels | The first and last token of the subtree |
| `token.is_ancestor(other)` | test | `True` if `other` is somewhere below the token |
All of these use the existing parse. Reading them is cheap and does not rerun the model.
Going down: children, lefts, rights
Start from a verb and look at what attaches to it.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The committee approved the new budget.")
verb = [t for t in doc if t.pos_ == "VERB"][0]
print("children:", [(c.text, c.dep_) for c in verb.children])
print("left:", [t.text for t in verb.lefts])
print("right:", [t.text for t in verb.rights])
print("subtree:", " ".join(t.text for t in verb.subtree))For this sentence the model normally produces these results:
childrenholdscommittee(nsubj),budget(dobj), and the final period (punct). It does not holdThe,the, ornew, because those attach to the nouns, not to the verb.leftsholds onlycommittee.rightsholdsbudgetand the period.subtreeis the whole sentence, because the verb is the root.
children is a generator-like iterator. Wrap it in list() if you need its length or want to loop over it twice. Use token.n_lefts + token.n_rights to count dependents without building a list.
Going up: ancestors and the root
ancestors follows head links until it reaches the root. It does not include the starting token itself.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The quick brown fox jumps over the lazy dog.")
dog = next(t for t in doc if t.text == "dog")
print([a.text for a in dog.ancestors])
for token in doc:
print(token.text, token.dep_, "->", token.head.text)For dog, the usual result is ['over', 'jumps']. The preposition is the first step up and the verb is the root. The ancestor list is useful for questions such as "is this word inside a prepositional phrase?" or "which verb governs this noun?"
You can write the same loop by hand. It ends because the root is its own head.
def path_to_root(token):
path = [token]
while token.head != token:
token = token.head
path.append(token)
return pathUse ancestors when you can. Write the explicit loop only when you need the starting token in the path, as above.
Testing containment
is_ancestor answers whether one token governs another, directly or indirectly.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The quick brown fox jumps over the lazy dog.")
verb = next(t for t in doc if t.dep_ == "ROOT")
dog = next(t for t in doc if t.text == "dog")
fox = next(t for t in doc if t.text == "fox")
print(verb.is_ancestor(dog))
print(fox.is_ancestor(dog))The first call is True because dog is somewhere below the root. The second is False because dog sits in the prepositional branch, not under fox.
Going across: subtrees as phrases
A subtree is how you recover a full phrase from a single head word. The subtree of fox is "The quick brown fox", and the subtree of over is "over the lazy dog". This is more reliable than guessing a window of nearby words.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The committee approved the new budget.")
for token in doc:
if token.dep_ in ("nsubj", "dobj"):
phrase = " ".join(t.text for t in token.subtree)
print(token.dep_, "->", phrase)For long phrases, a Span is often more convenient than a list of tokens. It keeps the character offsets and gives you .text directly.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The small team wrote a detailed report about the results.")
for token in doc:
if token.dep_ == "dobj":
span = doc[token.left_edge.i : token.right_edge.i + 1]
print(span.text)The slice uses right_edge.i + 1 because slices exclude their end index. Here the object is report, and its subtree includes the about the results attachment. The output is therefore "a detailed report about the results", not just "a detailed report". This is correct under the parse, but you may not want it. If you want only the modifiers before the noun, use token.lefts. If you want the noun with only some dependents, filter by dep_.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The small team wrote a detailed report about the results.")
report = next(t for t in doc if t.text == "report")
core = [t.text for t in report.lefts] + [report.text]
print(" ".join(core))Edge cases to know
- Subtrees are contiguous in most sentences. The slice
doc[left_edge.i : right_edge.i + 1]is safe when the tree is projective, meaning no dependency arcs cross. spaCy's English models produce projective trees, but a custom component or a different language model may not. If a subtree skips tokens, rebuild it fromtoken.subtreeinstead of slicing. - Punctuation belongs to subtrees. A comma or period attached to a head appears in that head's
subtree. Filter witht.is_punctwhen you build clean phrases. - The root's subtree is the whole sentence.
ROOT.subtreeis a quick way to get the sentence tokens. It does not cross sentence boundaries, because each sentence has its own root. - Coordination hangs on the first conjunct. In "apples and oranges",
orangesattaches toapplesasconj, andandattaches ascc. The subtree ofapplesthen contains the entire coordinated phrase. Usetoken.conjunctsto list the other members of a coordination without reading the labels yourself. - A token can be absent from a list you expect. A verb with no overt subject, as in an imperative such as "Close the door.", has an empty
leftsfor the subject role. Always handle empty results. - Heads can sit on either side. A dependent can appear to the left or right of its head. This is why
leftsandrightsare separate, and why you should not assume "subject on the left" without checking.
A reusable helper
This function combines the pieces. Given a token, it returns the phrase it heads without punctuation, and the verb that governs it, if there is one.
import spacy
nlp = spacy.load("en_core_web_sm")
def describe(token):
phrase = " ".join(t.text for t in token.subtree if not t.is_punct)
governing = next((a for a in token.ancestors if a.pos_ == "VERB"), None)
return phrase, governing.text if governing else None
doc = nlp("The quick brown fox jumps over the lazy dog.")
for token in doc:
if token.dep_ in ("nsubj", "pobj"):
print(token.text, "->", describe(token))For fox the result pairs "The quick brown fox" with jumps. For dog it pairs "the lazy dog" with jumps, because over is an adposition and jumps is the first verb found among the ancestors. The next(..., None) form keeps the function safe when no verb exists above the token, such as in a fragment.
Exercise
Using the sentence "The committee approved the new budget.", write code that prints, for each token whose dep_ is det or amod, the token, its head, and the full phrase that head governs. Then explain why is_ancestor returns False when you call it from The on budget.
Show answer
Code:
import spacy
nlp = spacy.load("encorewebsm")
doc = nlp("The committee approved the new budget.")
for token in doc:
if token.dep in ("det", "amod"):
head = token.head
phrase = " ".join(t.text for t in head.subtree)
print(token.text, "|", head.text, "|", phrase)
The tokens "The", "the", and "new" are printed with their noun heads ("committee" or "budget") and phrases such as "The committee" and "the new budget". is_ancestor returns False for The and budget because The is a leaf below committee. It governs no tokens, so budget is not in its subtree. The question is about going downward from the first token, and The has nothing below it.
Exercise
A colleague slices phrases with doc[token.i - 2 : token.i + 3] to get "the words around" a noun. Name two situations where token.subtree gives a better result, and one where the colleague's slice might be preferable.
Show answer
The subtree is better when the phrase is longer or shorter than five tokens, because the slice cuts long modifiers and includes unrelated neighbours around short ones. It is also better when you need exactly the words that depend on the noun, for example a modifier that follows it, such as a prepositional phrase. The fixed window may be preferable when you want raw surrounding context regardless of grammar, for instance to show a keyword in context, because it does not depend on the parse being right.