Get startedGet started for free

Complex components

In this exercise, you'll be writing a custom component that uses the PhraseMatcher to find animal names in the document and adds the matched spans to the doc.ents.

A PhraseMatcher with the animal patterns has already been created as the variable matcher. The small English model is available as the variable nlp. The Span object has already been imported for you.

This exercise is part of the course

Advanced NLP with spaCy

View Course

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Define the custom component
def animal_component(doc):
    # Apply the matcher to the doc
    matches = ____
    # Create a Span for each match and assign the label 'ANIMAL'
    spans = [Span(____, ____, ___, label=____)
             for match_id, start, end in matches]
    # Overwrite the doc.ents with the matched spans
    doc.ents = spans
    return doc
Edit and Run Code