Sub topic 12
Matching grammatical patterns with DependencyMatcher
Earlier chapters used children, subtree, and loops to pull relations out of a parse. That works, but each new relation needs a new hand-written loop. DependencyMatcher lets you describe a relation as a small pattern and have spaCy find every place in a Doc where it holds.
This chapter assumes you can load a pipeline, read dep_, head, and pos_, and know what a dependency tree looks like. It also assumes you have seen the token-based Matcher, though you do not need it.
What the matcher does
A DependencyMatcher searches the dependency tree of a parsed Doc. A pattern is a list of dictionaries. Each dictionary describes one token and, except for the first, how that token relates to a token already described. A pattern is therefore a small tree fragment.
The matcher needs dependency annotations. If you disabled the parser component, the Doc has no tree and matching will fail or return nothing useful. Load a pipeline that keeps the parser, such as en_core_web_sm.
Anatomy of a pattern
Each dictionary uses these keys:
RIGHT_ID: a name you choose for this token. Names must be unique within the pattern.RIGHT_ATTRS: token attributes the token must have, such asPOS,DEP,LEMMA,TAG, orORTH.LEFT_ID: the name of an earlier token this one is compared against.REL_OP: the relation operator between theLEFT_IDtoken and the new token.
The first dictionary is the anchor. It has only RIGHT_ID and RIGHT_ATTRS. Every later dictionary needs all four keys, and its LEFT_ID must name a token defined before it.
import spacy
from spacy.matcher import DependencyMatcher
nlp = spacy.load("en_core_web_sm")
matcher = DependencyMatcher(nlp.vocab)
pattern = [
{"RIGHT_ID": "verb", "RIGHT_ATTRS": {"POS": "VERB"}},
{
"LEFT_ID": "verb",
"REL_OP": ">",
"RIGHT_ID": "subject",
"RIGHT_ATTRS": {"DEP": "nsubj"},
},
]
matcher.add("VERB_SUBJECT", [pattern])
doc = nlp("The engineer fixed the bug.")
for match_id, token_ids in matcher(doc):
print(nlp.vocab.strings[match_id], [doc[i].text for i in token_ids])Each match is a tuple of a match ID and a list of token indices. The indices follow the order of the dictionaries in the pattern, so token_ids[0] is the verb and token_ids[1] is the subject. This is the main convenience of the matcher: you can unpack results by position instead of searching for them.
The diagram below shows the shape of a subject-verb-object pattern.
Relation operators
The operator is read as "LEFT_ID token, operator, new token". In >, the left token is the head of the new token.
| Operator | Meaning |
|---|---|
| `A > B` | A is the immediate head of B |
| `A < B` | A is an immediate dependent of B |
| `A >> B` | A is the head of B somewhere down a chain |
| `A << B` | A is a dependent of B somewhere up a chain |
| `A . B` | A immediately precedes B in the text |
| `A .* B` | A precedes B anywhere earlier in the text |
| `A ; B` | A immediately follows B |
| `A ;* B` | A follows B anywhere |
| `A $+ B` | B is the immediate right sibling of A (same head) |
| `A $- B` | B is the immediate left sibling of A |
| `A $++ B` | B is any right sibling of A |
| `A $-- B` | B is any left sibling of A |
Two details cause most operator mistakes:
>and<are direct links only. Use>>or<<when intervening words can appear, for example an adverb phrase between a verb and a noun that depends on it.- The word-order operators (
.,;, and their starred forms) look at positions in the text. The sibling operators look at the tree, so they only relate tokens that share a head.
A subject-verb-object pattern
The earlier loop-based extraction can be rewritten as a single pattern. Because label names differ between models and languages, the object attribute accepts either dobj or obj with the IN predicate.
import spacy
from spacy.matcher import DependencyMatcher
nlp = spacy.load("en_core_web_sm")
matcher = DependencyMatcher(nlp.vocab)
svo = [
{"RIGHT_ID": "verb", "RIGHT_ATTRS": {"POS": "VERB"}},
{
"LEFT_ID": "verb",
"REL_OP": ">",
"RIGHT_ID": "subject",
"RIGHT_ATTRS": {"DEP": "nsubj"},
},
{
"LEFT_ID": "verb",
"REL_OP": ">",
"RIGHT_ID": "object",
"RIGHT_ATTRS": {"DEP": {"IN": ["dobj", "obj"]}},
},
]
matcher.add("SVO", [svo])
doc = nlp("Researchers published the dataset and the editors reviewed the paper.")
for match_id, token_ids in sorted(matcher(doc), key=lambda m: m[1][0]):
verb, subj, obj = (doc[i] for i in token_ids)
print(subj.text, verb.lemma_, obj.text)Both subject and object use LEFT_ID: "verb". They are siblings in the pattern but are matched independently, so the matcher does not require any particular word order between them. The sorted call puts matches in text order, because the matcher does not promise a particular order.
The attribute predicates in RIGHT_ATTRS are the same ones the token-based Matcher uses. IN and NOT_IN test membership in a list. REGEX matches a regular expression against a string attribute. Matching on LEMMA is often more stable than matching on ORTH, because it covers inflected forms.
Matching a negated verb
Patterns are not limited to subjects and objects. This one finds verbs that have a negation dependent, using the neg label:
import spacy
from spacy.matcher import DependencyMatcher
nlp = spacy.load("en_core_web_sm")
matcher = DependencyMatcher(nlp.vocab)
negated = [
{"RIGHT_ID": "verb", "RIGHT_ATTRS": {"POS": "VERB"}},
{
"LEFT_ID": "verb",
"REL_OP": ">",
"RIGHT_ID": "negation",
"RIGHT_ATTRS": {"DEP": "neg"},
},
]
matcher.add("NEGATED_VERB", [negated])
doc = nlp("The team did not approve the plan.")
for match_id, token_ids in matcher(doc):
verb, neg = (doc[i] for i in token_ids)
print(f"{verb.lemma_} is negated by '{neg.text}'")Auxiliaries such as "did" are dependents of the main verb in spaCy's English annotation scheme, so the neg token attaches to "approve". Checking token.dep_ and token.head on a sample sentence before writing the pattern confirms where the label attaches in your model.
Several patterns, callbacks, and edge cases
You can pass more than one pattern to a single matcher.add call. The patterns act as alternatives under one name, like an OR. This is how you cover active and passive voice:
import spacy
from spacy.matcher import DependencyMatcher
nlp = spacy.load("en_core_web_sm")
matcher = DependencyMatcher(nlp.vocab)
active = [
{"RIGHT_ID": "verb", "RIGHT_ATTRS": {"POS": "VERB"}},
{"LEFT_ID": "verb", "REL_OP": ">", "RIGHT_ID": "subj",
"RIGHT_ATTRS": {"DEP": "nsubj"}},
]
passive = [
{"RIGHT_ID": "verb", "RIGHT_ATTRS": {"POS": "VERB"}},
{"LEFT_ID": "verb", "REL_OP": ">", "RIGHT_ID": "subj",
"RIGHT_ATTRS": {"DEP": "nsubjpass"}},
]
def report(matcher, doc, i, matches):
match_id, token_ids = matches[i]
verb, subj = (doc[t] for t in token_ids)
print(f"{subj.text} <- {verb.text}")
matcher.add("SUBJECT", [active, passive], on_match=report)
doc = nlp("The bug was fixed by the engineer.")
matcher(doc)The on_match callback receives the matcher, the Doc, the index of the current match, and the full match list. This chapter uses it to print, but it can also collect results or set extension attributes.
Keep these edge cases in mind:
- One anchor, many matches. If a verb has two direct objects in the parse, you get two matches with the same verb. Deduplicate by the anchor token if you need one result per verb.
- Coordination is not matched automatically. In "She bought apples and pears", "pears" is a
conjof "apples", not a direct object of "bought". A>pattern finds only "apples". Add a pattern with aconjnode, or followconjlinks in Python after matching. - Every named token must match. There are no optional nodes. To treat a node as optional, write separate patterns with and without it.
- Labels are model-specific.
nsubjpass,dobj, andnegbelong to English models of this generation. A different language or model version may use different names, so test on sample sentences. - Parse errors carry through. The matcher finds exactly what the tree says. If the parser attaches a phrase to the wrong head, the match is wrong or missing. The final chapter covers how to check for this.
When to use the matcher or plain Python
| Situation | Better choice |
|---|---|
| A fixed relation, with attributes known in advance, over many documents | `DependencyMatcher` |
| Several alternative patterns under one label | `DependencyMatcher` |
| Logic that depends on counts, other tokens, or conditions across sentences | Plain Python over `token.children` |
| Following variable-length chains such as conjunctions | Plain Python, or `>>` with care |
The matcher is declarative: the pattern states what to find, not how to walk the tree. Plain Python is more flexible when the rule needs real logic.
Exercise
Write a DependencyMatcher pattern that finds a verb together with a prepositional phrase attached directly to it (a dependent with dep_ "prep"), and print the verb and the preposition for "The package arrived on Monday." What would you change so that the pattern also matches when the preposition attaches to a noun that depends on the verb, as in "She read a book about birds"?
Show answer
Anchor on {"POS": "VERB"} with RIGHTID "verb". Add a second node with LEFTID "verb", RELOP ">", RIGHTID "prep", and RIGHTATTRS {"DEP": "prep"}. After matcher.add("VERBPREP", [pattern]), loop over matcher(doc) and print doc[tokenids[0]].text and doc[tokenids[1]].text. For the first sentence the verb is "arrived" and the preposition is "on". For the second case, the preposition is not a direct dependent of the verb, so ">" misses it. Change the operator to ">>" so the preposition can be anywhere below the verb in the tree. Alternatively, add a second pattern to the same matcher.add call that places a noun node between the verb and the preposition.