Named Entity Recognition — Hands-on
NER with spaCy (Industry-Standard, Pre-trained)
import spacy
nlp = spacy.load("en_core_web_sm")
text = "Riya joined Google in Bengaluru on 5 August 2026 for a package of ₹18,00,000."
doc = nlp(text)
for ent in doc.ents:
print(ent.text, "->", ent.label_)
# Riya -> PERSON
# Google -> ORG
# Bengaluru -> GPE
# 5 August 2026 -> DATE
# ₹18,00,000 -> MONEY
Visualizing Entities
from spacy import displacy
displacy.render(doc, style="ent") # renders inline HTML highlighting each entity
NER with NLTK (Chunking-based)
import nltk
from nltk import pos_tag, word_tokenize, ne_chunk
text = "Riya joined Google in Bengaluru."
tree = ne_chunk(pos_tag(word_tokenize(text)))
print(tree)
# (S
# (PERSON Riya/NNP)
# joined/VBD
# (ORGANIZATION Google/NNP)
# in/IN
# (GPE Bengaluru/NNP)
# ./.)
Extracting Only PERSON and ORG Entities
import spacy
nlp = spacy.load("en_core_web_sm")
text = "Sundar Pichai leads Google, while Satya Nadella leads Microsoft."
doc = nlp(text)
people = [ent.text for ent in doc.ents if ent.label_ == "PERSON"]
orgs = [ent.text for ent in doc.ents if ent.label_ == "ORG"]
print("People:", people) # ['Sundar Pichai', 'Satya Nadella']
print("Orgs: ", orgs) # ['Google', 'Microsoft']
Building a Simple Gazetteer-based (Rule) NER for a Custom Domain
Pre-trained NER models won't recognize domain-specific entities (e.g. course names, internal product codes). spaCy allows adding custom entity rules:
import spacy
from spacy.pipeline import EntityRuler
nlp = spacy.load("en_core_web_sm")
ruler = nlp.add_pipe("entity_ruler", before="ner")
patterns = [
{"label": "COURSE", "pattern": "Natural Language Processing"},
{"label": "COURSE", "pattern": "Data Structures"},
]
ruler.add_patterns(patterns)
doc = nlp("This semester I am studying Natural Language Processing and Data Structures.")
for ent in doc.ents:
print(ent.text, ent.label_)
# Natural Language Processing -> COURSE
# Data Structures -> COURSE
Real-World NER Applications
| Application | How NER is used |
|---|---|
| Resume parsing | Extract candidate name, skills, companies, degrees |
| News aggregation | Tag articles by mentioned people/organizations/places |
| Customer support | Extract order IDs, product names, dates from tickets |
| Search engines | Improve query understanding ("weather in Paris" → LOC=Paris) |
| Legal/finance | Extract clause parties, monetary amounts, dates from contracts |
NER output (structured entity tags) directly feeds into Information Extraction systems, which we cover in Unit 3.