A text analysis tool that extracts named entities from any text — people, organisations, locations, dates, and money — and exports coloured HTML or structured JSON.
spaCy can identify 18 types of named entities out of the box using a pre-trained model.
import spacy
# Load the small English model (~12 MB)
nlp = spacy.load('en_core_web_sm')
text = """
Apple Inc. announced on Tuesday that CEO Tim Cook will present at the
World Economic Forum in Davos, Switzerland next January. The company
reported revenue of $94.9 billion in Q1 2024, up 2% from the previous year.
Elon Musk, who owns Tesla and SpaceX, commented that the figure was impressive.
"""
doc = nlp(text)
for ent in doc.ents:
print(f"{ent.text:<30} {ent.label_:<15} {spacy.explain(ent.label_)}")
Apple Inc. ORG Companies, agencies, institutions Tuesday DATE Absolute or relative dates Tim Cook PERSON People, inc. fictional World Economic Forum ORG Companies, agencies, institutions Davos GPE Countries, cities, states Switzerland GPE Countries, cities, states January DATE Absolute or relative dates $94.9 billion MONEY Monetary values Q1 2024 DATE Absolute or relative dates 2% PERCENT Percentage Elon Musk PERSON People, inc. fictional Tesla ORG Companies, agencies, institutions SpaceX ORG Companies, agencies, institutions
Collect all entities into a dictionary by label for easy downstream use.
from collections import defaultdict
def extract_entities(text):
doc = nlp(text)
entities = defaultdict(list)
for ent in doc.ents:
entities[ent.label_].append(ent.text)
# Deduplicate
return {k: list(dict.fromkeys(v)) for k, v in entities.items()}
result = extract_entities(text)
for label, items in result.items():
print(f"{spacy.explain(label):25} {items}")
Companies, agencies ['Apple Inc.', 'World Economic Forum', 'Tesla', 'SpaceX'] Dates ['Tuesday', 'January', 'Q1 2024'] People ['Tim Cook', 'Elon Musk'] Countries, cities ['Davos', 'Switzerland'] Monetary values ['$94.9 billion'] Percentage ['2%']
spaCy can render coloured HTML highlighting for each entity type.
from spacy import displacy
html = displacy.render(doc, style='ent', page=True)
with open('entities.html', 'w', encoding='utf-8') as f:
f.write(html)
print("Saved to entities.html — open it in a browser to see colour-coded entities")
You extracted structured information from unstructured text automatically. NER is used in news aggregators (extract companies and people from articles), financial analysis (extract figures and dates from filings), and CRM systems (auto-tag contacts from emails).
Spotted a bug, broken code, or something that doesn't look right? Tell us what's off and we'll fix it.