Sub topic 2
Lemmas, Dependencies, and the Parse Tree
This chapter assumes you can load a spaCy pipeline with spacy.load("en_core_web_sm"), read a Doc, and loop over its tokens. You should also know basic grammar terms such as subject, verb, and object.
Lemmas and why they depend on POS
A lemma is the dictionary base form of a word. The lemma of "running" is "run". spaCy assigns lemmas with rules that use the part-of-speech (POS) tag, so the same spelling can map to different lemmas. "Saw" can be a past-tense verb (lemma "see") or a noun (lemma "saw").
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("I saw the saw in the shed.")
for token in doc:
print(token.text, token.pos_, token.lemma_)Dependency relations: dep_ and head
Each token has a dep_ label that names its grammatical role, and a head that points to the token it depends on. The root of the sentence is its own head. Read the arcs as "this token is the dep_ of that head."
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The committee approved the new budget.")
for token in doc:
print(token.text, token.dep_, token.head.text)Sentence boundaries from the parse
The parser also sets sentence boundaries. Iterate over doc.sents to get each sentence as a span.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The model runs fast. It also uses little memory.")
for sent in doc.sents:
print(sent.text)Seeing the tree with displaCy
displaCy draws the dependency tree. displacy.render returns SVG markup, which you can save to a file and open in a browser.
import spacy
from spacy import displacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The committee approved the new budget.")
svg = displacy.render(doc, style="dep", jupyter=False)
with open("tree.svg", "w", encoding="utf-8") as f:
f.write(svg)Walking the tree: children, subtree, ancestors
Use children to get a token's direct dependents, subtree to get every token under it, and ancestors to climb toward the root.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The committee approved the new budget.")
verb = doc[2]
print("children:", [c.text for c in verb.children])
print("subtree:", " ".join(t.text for t in verb.subtree))
budget = doc[6]
print("ancestors:", [a.text for a in budget.ancestors])Exercise
For the sentence "Dogs chase cats.", which token is the root, and what is the dep_ of "cats"?
Show answer
"chase" is the root, because it is its own head. "cats" has the dependency label "dobj", meaning direct object.