Sub topic 12
Matching Grammatical Patterns with DependencyMatcher
Prerequisites: You should know basic Python, spaCy pipelines, tokens, part-of-speech tags, and dependency labels such as nsubj and obj.
A dependency parse represents a sentence as a tree. Each token points to its syntactic head, and dep_ describes its relationship to that head. For example, in “The engineer fixed the bug,” the verb fixed governs both the subject engineer and the object bug.
DependencyMatcher finds these relationships directly. This is more flexible than matching a fixed sequence of words because the words can be separated by adjectives, adverbs, or other phrases.
How a dependency pattern works
A pattern gives important tokens names with RIGHT_ID. Each later pattern entry connects a new token to an earlier token with LEFT_ID and REL_OP.
The > operator means that the left token is the head of the right token. Therefore, this relation searches for a child of a verb:
| Pattern part | Meaning |
|---|---|
| `POS: VERB` | Find a verb |
| `DEP: nsubj` | Find a nominal subject |
| `REL_OP: >` | The verb governs the subject |
The following diagram shows the relationship being matched:
Finding subject-verb-object relations
This example finds a verb with both a nominal subject and an object. It prints the matched token texts.
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"},
},
{
"LEFT_ID": "verb",
"REL_OP": ">",
"RIGHT_ID": "object",
"RIGHT_ATTRS": {"DEP": {"IN": ["obj", "dobj"]}},
},
]
matcher.add("SUBJECT_VERB_OBJECT", [pattern])
doc = nlp("The engineer fixed the bug. The tester reported an error.")
for match_id, token_ids in matcher(doc):
matched = {name: doc[token_ids[i]].text
for i, name in enumerate(["verb", "subject", "object"])}
print(matched)The output is similar to:
{'verb': 'fixed', 'subject': 'engineer', 'object': 'bug'}
{'verb': 'reported', 'subject': 'tester', 'object': 'error'}The RIGHT_ATTRS value accepts token attributes such as POS, DEP, LEMMA, and LOWER. You can require a particular verb lemma, for example {"LEMMA": "approve"}, or allow several dependency labels with the IN operator.
The exact object label depends on the language and model. Older English models may use dobj, while newer Universal Dependencies-style models commonly use obj. Check real output before writing a production pattern.
Checking and debugging matches
Start with a small sentence whose parse you understand. Print token details before making the pattern more general:
for token in doc:
print(token.text, token.pos_, token.dep_, token.head.text)If no matches appear, check these common causes:
- The model uses a different dependency label.
- The sentence has no direct object.
- The token is tagged as
AUXinstead ofVERB. - The parser attached the subject or object to another head.
- The relation operator points in the wrong direction.
For complex grammar, add one relation at a time. First match the verb and subject. Then add the object, clauses, or descendants with operators such as >>.
Exercise
How would you change the pattern so it matches only verbs whose lemma is "publish"?
Show answer
Add "LEMMA": "publish" to the verb's RIGHT_ATTRS, alongside "POS": "VERB".