Get startedGet started for free

Creating a custom named entity in spaCy

If spaCy's built-in named entities aren't enough, you can make your own using spaCy's entity_ruler pipeline component.

The entity_ruler component allows you to create your own entities and add them to a spaCy pipeline.

You start by adding the component to the existing pipeline with nlp.add_pipe(), placing it before the "ner" component so your own rules are applied first. add_pipe() returns the component it added.

You can then call add_patterns() on the component and pass it a dictionary of the text pattern you'd like to label with an entity.

Since Acme is a technology company, you decide to tag the pattern "smartphone" with the "PRODUCT" entity tag.

spaCy has been imported and nlp holds a loaded en_core_web_sm model. Since changing a pipeline has no effect on docs that already exist, you'll recreate the doc from the transcribed text of call_4_channel_2.wav file once the new component is in place.

This exercise is part of the course

Spoken Language Processing in Python

View Course

Exercise instructions

  • Add the "entity_ruler" component to the nlp pipeline, before the "ner" component, and save it to ruler.
  • Add "smartphone" as the value for the "pattern" key.
  • Print the entity attributes contained in doc.

Hands-on interactive exercise

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

# Add an entity_ruler component to the pipeline, before ner
ruler = nlp.add_pipe(____, before=____)

# Define pattern for new entity
ruler.add_patterns([{"label": "PRODUCT", "pattern": ____}])

# Recreate the doc so it uses the updated pipeline
doc = nlp(call_4_channel_2_text)

# Test new entity
for entity in doc.____:
  print(entity.text, entity.label_)
Edit and Run Code