2020-07-27 16:11:45 +00:00
---
title: DependencyMatcher
2020-08-31 18:04:26 +00:00
teaser: Match subtrees within a dependency parse
2020-07-27 16:11:45 +00:00
tag: class
2020-08-31 18:04:26 +00:00
new: 3
2020-07-27 16:11:45 +00:00
source: spacy/matcher/dependencymatcher.pyx
---
2020-08-09 20:31:52 +00:00
The `DependencyMatcher` follows the same API as the [`Matcher` ](/api/matcher )
and [`PhraseMatcher` ](/api/phrasematcher ) and lets you match on dependency trees
2020-08-31 18:04:26 +00:00
using
[Semgrex operators ](https://nlp.stanford.edu/nlp/javadoc/javanlp/edu/stanford/nlp/semgraph/semgrex/SemgrexPattern.html ).
2020-08-09 20:31:52 +00:00
It requires a pretrained [`DependencyParser` ](/api/parser ) or other component
2020-09-04 14:30:31 +00:00
that sets the `Token.dep` and `Token.head` attributes. See the
[usage guide ](/usage/rule-based-matching#dependencymatcher ) for examples.
2020-08-09 20:31:52 +00:00
## Pattern format {#patterns}
2020-08-31 18:04:26 +00:00
> ```python
2020-08-09 20:31:52 +00:00
> ### Example
2020-08-31 18:04:26 +00:00
> # pattern: "[subject] ... initially founded"
2020-08-09 20:31:52 +00:00
> [
2020-08-31 18:04:26 +00:00
> # anchor token: founded
2020-08-09 20:31:52 +00:00
> {
2020-08-31 18:04:26 +00:00
> "RIGHT_ID": "founded",
> "RIGHT_ATTRS": {"ORTH": "founded"}
2020-08-09 20:31:52 +00:00
> },
2020-08-31 18:04:26 +00:00
> # founded -> subject
2020-08-09 20:31:52 +00:00
> {
2020-08-31 18:04:26 +00:00
> "LEFT_ID": "founded",
> "REL_OP": ">",
> "RIGHT_ID": "subject",
> "RIGHT_ATTRS": {"DEP": "nsubj"}
2020-08-09 20:31:52 +00:00
> },
2020-08-31 18:04:26 +00:00
> # "founded" follows "initially"
2020-08-09 20:31:52 +00:00
> {
2020-08-31 18:04:26 +00:00
> "LEFT_ID": "founded",
> "REL_OP": ";",
> "RIGHT_ID": "initially",
> "RIGHT_ATTRS": {"ORTH": "initially"}
2020-08-09 20:31:52 +00:00
> }
> ]
> ```
A pattern added to the `DependencyMatcher` consists of a list of dictionaries,
2020-08-31 18:04:26 +00:00
with each dictionary describing a token to match. Except for the first
dictionary, which defines an anchor token using only `RIGHT_ID` and
`RIGHT_ATTRS` , each pattern should have the following keys:
| Name | Description |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
2020-09-04 14:30:31 +00:00
| `LEFT_ID` | The name of the left-hand node in the relation, which has been defined in an earlier node. ~~str~~ |
2020-08-31 18:04:26 +00:00
| `REL_OP` | An operator that describes how the two nodes are related. ~~str~~ |
| `RIGHT_ID` | A unique name for the right-hand node in the relation. ~~str~~ |
| `RIGHT_ATTRS` | The token attributes to match for the right-hand node in the same format as patterns provided to the regular token-based [`Matcher` ](/api/matcher ). ~~Dict[str, Any]~~ |
2020-09-04 14:30:31 +00:00
< Infobox title = "Designing dependency matcher patterns" emoji = "📖" >
2020-08-31 18:04:26 +00:00
2020-09-04 14:30:31 +00:00
For examples of how to construct dependency matcher patterns for different types
of relations, see the usage guide on
[dependency matching ](/usage/rule-based-matching#dependencymatcher ).
2020-08-31 18:04:26 +00:00
2020-09-04 14:30:31 +00:00
< / Infobox >
2020-08-31 18:04:26 +00:00
2022-07-27 11:16:44 +00:00
### Operators {#operators}
2020-08-31 18:04:26 +00:00
The following operators are supported by the `DependencyMatcher` , most of which
come directly from
[Semgrex ](https://nlp.stanford.edu/nlp/javadoc/javanlp/edu/stanford/nlp/semgraph/semgrex/SemgrexPattern.html ):
2020-09-04 14:30:31 +00:00
| Symbol | Description |
| --------- | -------------------------------------------------------------------------------------------------------------------- |
| `A < B` | `A` is the immediate dependent of `B` . |
| `A > B` | `A` is the immediate head of `B` . |
| `A << B` | `A` is the dependent in a chain to `B` following dep → head paths. |
| `A >> B` | `A` is the head in a chain to `B` following head → dep paths. |
| `A . B` | `A` immediately precedes `B` , i.e. `A.i == B.i - 1` , and both are within the same dependency tree. |
| `A .* B` | `A` precedes `B` , i.e. `A.i < B.i` , and both are within the same dependency tree _(not in Semgrex)_ . |
| `A ; B` | `A` immediately follows `B` , i.e. `A.i == B.i + 1` , and both are within the same dependency tree _(not in Semgrex)_ . |
| `A ;* B` | `A` follows `B` , i.e. `A.i > B.i` , and both are within the same dependency tree _(not in Semgrex)_ . |
| `A $+ B` | `B` is a right immediate sibling of `A` , i.e. `A` and `B` have the same parent and `A.i == B.i - 1` . |
| `A $- B` | `B` is a left immediate sibling of `A` , i.e. `A` and `B` have the same parent and `A.i == B.i + 1` . |
| `A $++ B` | `B` is a right sibling of `A` , i.e. `A` and `B` have the same parent and `A.i < B.i` . |
| `A $-- B` | `B` is a left sibling of `A` , i.e. `A` and `B` have the same parent and `A.i > B.i` . |
2022-07-27 11:16:44 +00:00
| `A >++ B` | `B` is a right child of `A` , i.e. `A` is a parent of `B` and `A.i < B.i` _(not in Semgrex)_ . |
| `A >-- B` | `B` is a left child of `A` , i.e. `A` is a parent of `B` and `A.i > B.i` _(not in Semgrex)_ . |
| `A <++ B` | `B` is a right parent of `A` , i.e. `A` is a child of `B` and `A.i < B.i` _(not in Semgrex)_ . |
| `A <-- B` | `B` is a left parent of `A` , i.e. `A` is a child of `B` and `A.i > B.i` _(not in Semgrex)_ . |
2020-08-09 20:31:52 +00:00
## DependencyMatcher.\_\_init\_\_ {#init tag="method"}
2020-08-31 18:04:26 +00:00
Create a `DependencyMatcher` .
2020-08-09 20:31:52 +00:00
> #### Example
>
> ```python
> from spacy.matcher import DependencyMatcher
> matcher = DependencyMatcher(nlp.vocab)
> ```
2020-08-31 18:04:26 +00:00
| Name | Description |
| -------------- | ----------------------------------------------------------------------------------------------------- |
| `vocab` | The vocabulary object, which must be shared with the documents the matcher will operate on. ~~Vocab~~ |
| _keyword-only_ | |
| `validate` | Validate all patterns added to this matcher. ~~bool~~ |
2020-08-09 20:31:52 +00:00
## DependencyMatcher.\_\call\_\_ {#call tag="method"}
2020-08-31 18:04:26 +00:00
Find all tokens matching the supplied patterns on the `Doc` or `Span` .
2020-08-09 20:31:52 +00:00
> #### Example
>
> ```python
2020-08-17 14:45:24 +00:00
> from spacy.matcher import DependencyMatcher
2020-08-09 20:31:52 +00:00
>
2020-08-17 14:45:24 +00:00
> matcher = DependencyMatcher(nlp.vocab)
2020-08-31 18:04:26 +00:00
> pattern = [{"RIGHT_ID": "founded_id",
> "RIGHT_ATTRS": {"ORTH": "founded"}}]
> matcher.add("FOUNDED", [pattern])
2020-08-09 20:31:52 +00:00
> doc = nlp("Bill Gates founded Microsoft.")
> matches = matcher(doc)
> ```
2020-08-31 18:04:26 +00:00
| Name | Description |
| ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `doclike` | The `Doc` or `Span` to match over. ~~Union[Doc, Span]~~ |
| **RETURNS** | A list of `(match_id, token_ids)` tuples, describing the matches. The `match_id` is the ID of the match pattern and `token_ids` is a list of token indices matched by the pattern, where the position of each token in the list corresponds to the position of the node specification in the pattern. ~~List[Tuple[int, List[int]]]~~ |
2020-08-09 20:31:52 +00:00
## DependencyMatcher.\_\_len\_\_ {#len tag="method"}
2020-08-31 18:04:26 +00:00
Get the number of rules added to the dependency matcher. Note that this only
returns the number of rules (identical with the number of IDs), not the number
of individual patterns.
2020-08-09 20:31:52 +00:00
> #### Example
>
> ```python
> matcher = DependencyMatcher(nlp.vocab)
> assert len(matcher) == 0
2020-08-31 18:04:26 +00:00
> pattern = [{"RIGHT_ID": "founded_id",
> "RIGHT_ATTRS": {"ORTH": "founded"}}]
> matcher.add("FOUNDED", [pattern])
2020-08-09 20:31:52 +00:00
> assert len(matcher) == 1
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | ---------------------------- |
| **RETURNS** | The number of rules. ~~int~~ |
2020-08-09 20:31:52 +00:00
## DependencyMatcher.\_\_contains\_\_ {#contains tag="method"}
Check whether the matcher contains rules for a match ID.
> #### Example
>
> ```python
2020-08-31 18:04:26 +00:00
> matcher = DependencyMatcher(nlp.vocab)
> assert "FOUNDED" not in matcher
> matcher.add("FOUNDED", [pattern])
> assert "FOUNDED" in matcher
2020-08-09 20:31:52 +00:00
> ```
2020-08-17 14:45:24 +00:00
| Name | Description |
| ----------- | -------------------------------------------------------------- |
| `key` | The match ID. ~~str~~ |
| **RETURNS** | Whether the matcher contains rules for this match ID. ~~bool~~ |
2020-08-09 20:31:52 +00:00
## DependencyMatcher.add {#add tag="method"}
Add a rule to the matcher, consisting of an ID key, one or more patterns, and an
optional callback function to act on the matches. The callback function will
receive the arguments `matcher` , `doc` , `i` and `matches` . If a pattern already
exists for the given ID, the patterns will be extended. An `on_match` callback
will be overwritten.
> #### Example
>
> ```python
> def on_match(matcher, doc, id, matches):
> print('Matched!', matches)
>
2020-08-17 14:45:24 +00:00
> matcher = DependencyMatcher(nlp.vocab)
2020-08-31 18:04:26 +00:00
> matcher.add("FOUNDED", patterns, on_match=on_match)
2020-08-09 20:31:52 +00:00
> ```
2020-08-31 18:04:26 +00:00
| Name | Description |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `match_id` | An ID for the patterns. ~~str~~ |
| `patterns` | A list of match patterns. A pattern consists of a list of dicts, where each dict describes a token in the tree. ~~List[List[Dict[str, Union[str, Dict]]]]~~ |
2020-09-12 15:38:54 +00:00
| _keyword-only_ | |
2020-08-31 18:04:26 +00:00
| `on_match` | Callback function to act on matches. Takes the arguments `matcher` , `doc` , `i` and `matches` . ~~Optional[Callable[[DependencyMatcher, Doc, int, List[Tuple], Any]]~~ |
2020-08-09 20:31:52 +00:00
2020-08-31 18:04:26 +00:00
## DependencyMatcher.get {#get tag="method"}
2020-08-09 20:31:52 +00:00
2020-08-31 18:04:26 +00:00
Retrieve the pattern stored for a key. Returns the rule as an
`(on_match, patterns)` tuple containing the callback and available patterns.
2020-08-09 20:31:52 +00:00
> #### Example
>
> ```python
2020-08-31 18:04:26 +00:00
> matcher.add("FOUNDED", patterns, on_match=on_match)
> on_match, patterns = matcher.get("FOUNDED")
2020-08-09 20:31:52 +00:00
> ```
2020-08-31 18:04:26 +00:00
| Name | Description |
| ----------- | ----------------------------------------------------------------------------------------------------------- |
| `key` | The ID of the match rule. ~~str~~ |
| **RETURNS** | The rule, as an `(on_match, patterns)` tuple. ~~Tuple[Optional[Callable], List[List[Union[Dict, Tuple]]]]~~ |
2020-08-09 20:31:52 +00:00
2020-08-31 18:04:26 +00:00
## DependencyMatcher.remove {#remove tag="method"}
2020-08-09 20:31:52 +00:00
2020-08-31 18:04:26 +00:00
Remove a rule from the dependency matcher. A `KeyError` is raised if the match
ID does not exist.
2020-08-09 20:31:52 +00:00
> #### Example
>
> ```python
2020-08-31 18:04:26 +00:00
> matcher.add("FOUNDED", patterns)
> assert "FOUNDED" in matcher
> matcher.remove("FOUNDED")
> assert "FOUNDED" not in matcher
2020-08-09 20:31:52 +00:00
> ```
2020-08-31 18:04:26 +00:00
| Name | Description |
| ----- | --------------------------------- |
| `key` | The ID of the match rule. ~~str~~ |