Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 4

Custom Entity Extraction with spaCy's Matcher

Recommended resources

Welcome to the final lesson of our first module on practical NLP with spaCy. In our previous session, we explored how to use linguistic features like part-of-speech tags and dependency parses to manually extract information. We built a function to find purchased items by programmatically navigating the dependency tree. This approach, while effective, can become complex to write and maintain as rules grow.

Today, we will formalize and scale that logic using spaCy's powerful rule-based Matcher. This lesson will show you how to implement custom entity and phrase extraction by defining declarative patterns. Instead of writing procedural code to find sequences of tokens, you will learn to describe the tokens you're looking for based on their attributes. This is a crucial skill for rapidly building information extraction systems for patterns you can define explicitly.

Introducing the Matcher: Patterns for Linguistic Structures

At its core, the spaCy Matcher is an engine that finds sequences of tokens based on user-defined patterns. Unlike regular expressions, which operate on raw strings, the Matcher operates on Doc and Token objects. This allows you to create patterns that leverage the rich linguistic annotations produced by the spaCy pipeline, such as POS, LEMMA, and DEP_, which we covered in the previous lesson.

A pattern is a list of dictionaries, where each dictionary defines the attributes of a single token you want to match. This declarative approach makes your extraction logic cleaner and more maintainable.

The following short video from DataCamp provides a clear and concise introduction to the Matcher and the structure of its patterns.

Python Tutorial: Rule-based Matching

This video offers a quick tour of what the Matcher is, how to define patterns, and how to use it to find matches in a document.

Watch the first two minutes to get a solid grasp of the core concepts: First, understand what the Matcher does and how it differs from regular expressions. Next, see how patterns are defined as lists of dictionaries, each describing a token's attributes. Finally, observe the basic workflow of initializing the Matcher, adding a pattern, and retrieving matches.


Defining Your First Pattern

Let's put this into practice. The process involves three main steps:

  1. Initialize the Matcher with the shared vocabulary (nlp.vocab).
  2. Define a pattern as a list of dictionaries.
  3. Add the pattern to the Matcher with a unique name.

Here's an example that finds full names, assuming a name consists of two consecutive proper nouns. This directly uses the POS attribute you learned about in the last lesson.

import spacy
from spacy.matcher import Matcher

nlp = spacy.load("en_core_web_sm")
matcher = Matcher(nlp.vocab)




# Define the pattern: two consecutive proper nouns
pattern = [{"POS": "PROPN"}, {"POS": "PROPN"}]




# Add the pattern to the matcher
matcher.add("FULL_NAME", [pattern])

doc = nlp("Gus Proto is a Python developer working for a London-based Fintech company.")
matches = matcher(doc)




# Iterate over the matches and print the resulting span
for match_id, start, end in matches:
    span = doc[start:end]
    print(f"Match found: {span.text}")




# Output: Match found: Gus Proto

As you can see, we didn't have to write a for loop checking token attributes. We simply declared the pattern we wanted to find. The Real Python article you've seen before provides this and another excellent example.

Natural Language Processing With spaCy in Python

This section of the article provides clear, self-contained examples of rule-based matching.

Please review the section on Rule-Based Matching. Pay close attention to the two code examples. The first one, extracting "Gus Proto", reinforces what we just did. The second, for extracting a phone number, introduces more advanced attributes like SHAPE and ORTH.


Crafting More Complex Patterns

The power of the Matcher comes from the variety of token attributes and operators you can use. You can match on almost any attribute of a Token object.

The spaCy Rule-based Matcher Explorer provides an interactive interface for building and testing token patterns. It visually demonstrates how dictionaries of attributes like `POS`, `LEMMA`, and `OP` correspond to tokens in a text.

Some of the most useful attributes for patterns include:

  • TEXT: The exact verbatim text (e.g., "Apple").
  • LOWER: The lowercase text (e.g., "apple").
  • LEMMA: The base form of the word (e.g., "buy" for "buying").
  • POS: The simple part-of-speech tag (e.g., NOUN, VERB).
  • SHAPE: The abstract shape of the word (e.g., dddd for a 4-digit number).
  • IS_PUNCT, IS_DIGIT, etc.: Boolean flags for token properties.

You can also use operators to specify how many times a token pattern should match. This is done by adding the 'OP' key to a token's dictionary.

  • '?': Makes the pattern optional (matches 0 or 1 time).
  • '+': Matches 1 or more times.
  • '*': Matches 0 or more times.
  • '!': Negates the pattern (matches 0 times).

The official spaCy documentation provides the definitive reference for all available attributes and operators.

Rule-based matching · spaCy Usage Documentation

This part of the documentation is your reference manual for the Matcher.

First, read the brief introduction to token-based matching. Then, review the table of Available token attributes to see what you can match on. Finally, look at the table of Operators and quantifiers to understand how to add flexibility to your patterns.

The following video provides a very clear, step-by-step demonstration of building a pattern, incorporating an operator, and retrieving the results as Span objects, which is a common and convenient practice.

Defining pattern rules for spaCy Matcher

This video walks through the process of defining, adding, and using a pattern rule with helpful explanations.

Watch the segment on defining a simple pattern using POS tags. Next, see how to add the rule and get matches, paying attention to the as_spans=True argument, which simplifies getting Span objects. Finally, see how operators like + are used to make patterns more flexible.


From Matches to Entities: The EntityRuler

The Matcher is excellent for finding sequences of tokens. However, a common next step is to add these found sequences to the doc.ents as named entities, just like the ones predicted by the statistical NER model.

For this task, spaCy provides a specialized pipeline component called the EntityRuler. It's a highly efficient component that takes a set of patterns and adds matching spans to doc.ents. It's essentially a production-ready version of the Matcher workflow, integrated directly into your nlp pipeline.

The EntityRuler can be added to your pipeline and configured with patterns. A key feature is its interaction with the statistical NER model.

  • If you add the EntityRuler before the "ner" component, the statistical model will respect the entities found by your rules and adjust its predictions accordingly. This is a powerful way to fix common NER errors or guide the model.
  • If you add it after the "ner" component, it will add entities to doc.ents only if they don't overlap with existing ones.

Let's see an example. Suppose the default model doesn't recognize "Google I/O" as a single EVENT. We can force it to do so with the EntityRuler.

import spacy

nlp = spacy.load("en_core_web_sm")
text = "At Google I/O 2023, the new Pixel was announced."

print("Entities before EntityRuler:")
for ent in nlp(text).ents:
    print(f"- {ent.text} ({ent.label_})")




# Create the EntityRuler
# The 'validate=True' flag helps catch errors in your patterns
ruler = nlp.add_pipe("entity_ruler", before="ner", config={"validate": True})




# Define the pattern for "Google I/O"
# This is a "phrase pattern", an exact string match.
patterns = [{"label": "EVENT", "pattern": "Google I/O"}]




# Add patterns to the ruler
ruler.add_patterns(patterns)

print("\nEntities after EntityRuler:")
doc = nlp(text)
for ent in doc.ents:
    print(f"- {ent.text} ({ent.label_})")




# Output before:
# - Google (ORG)
# - I/O 2023 (DATE)
#
# Output after:
# - Google I/O (EVENT)
# - 2023 (DATE)
# - Pixel (PERSON) -> Note: NER model still makes its own predictions, sometimes imperfectly!

Notice how the EntityRuler, placed before ner, forced the pipeline to recognize "Google I/O" as a single EVENT, overriding the initial ORG and DATE predictions.

Rule-based matching · spaCy Usage Documentation

This is the most important section for putting rule-based matching into a production pipeline.

Please read the entire section on the EntityRuler. Focus on understanding the pattern format, how to add the component to the pipeline using nlp.add_pipe, and the critical difference between adding it before versus after the "ner" component.


Conclusion

In this lesson, you've transitioned from manual, procedural rule-writing to a declarative, powerful pattern-matching system. This formalizes the ad-hoc extraction we experimented with previously and provides a robust tool for any NLP task where you can define explicit patterns.

Your key takeaways are:

  • The Matcher finds sequences of tokens based on patterns, which are lists of dictionaries describing token attributes.
  • Patterns can leverage rich linguistic features (POS, LEMMA, DEP_) and use operators (?, +, *) for added flexibility.
  • The EntityRuler is a pipeline component that uses these patterns to efficiently add custom entities to doc.ents.
  • Placing the EntityRuler before the ner component allows you to correct and guide the statistical model, improving overall accuracy for your specific use case.

This lesson concludes our module on practical NLP with spaCy. You now have a solid foundation in processing text, analyzing its linguistic structure, and extracting information using both statistical models and explicit rules.

In our next module, we will move into the world of transformer models with the Hugging Face ecosystem. While rule-based methods are excellent for known patterns, transformers excel at tasks that require a deeper contextual understanding and the ability to generalize from vast amounts of data. We'll start by learning how to load and use pre-trained models for common NLP tasks.