Learn SPACY with Real Code Examples
Updated Nov 24, 2025
Code Sample Descriptions
1
spaCy Named Entity Recognition Example
import spacy
# Load English model
nlp = spacy.load('en_core_web_sm')
# Sample text
doc = nlp('Apple is looking at buying U.K. startup for $1 billion')
# Print named entities
for ent in doc.ents:
print(ent.text, ent.label_)
A minimal spaCy example performing named entity recognition on a sample text.
2
spaCy Tokenization Example
import spacy
nlp = spacy.load('en_core_web_sm')
text = 'SpaCy is an amazing NLP library.'
doc = nlp(text)
# Print tokens
for token in doc:
print(token.text)
Splits text into tokens using spaCy tokenizer.
3
spaCy Part-of-Speech Tagging Example
import spacy
nlp = spacy.load('en_core_web_sm')
text = 'SpaCy is fast and accurate.'
doc = nlp(text)
# Print token POS tags
for token in doc:
print(token.text, token.pos_, token.tag_)
Tags each token with its part-of-speech (POS) label.
4
spaCy Dependency Parsing Example
import spacy
nlp = spacy.load('en_core_web_sm')
text = 'SpaCy parses text efficiently.'
doc = nlp(text)
# Print dependencies
for token in doc:
print(token.text, token.dep_, token.head.text)
Displays syntactic dependencies between tokens.
5
spaCy Lemmatization Example
import spacy
nlp = spacy.load('en_core_web_sm')
text = 'running runs ran'
doc = nlp(text)
# Print lemmas
for token in doc:
print(token.text, token.lemma_)
Extracts the base form (lemma) of each token.
6
spaCy Sentence Segmentation Example
import spacy
nlp = spacy.load('en_core_web_sm')
text = 'SpaCy is fast. It is easy to use.'
doc = nlp(text)
# Print sentences
for sent in doc.sents:
print(sent.text)
Splits text into sentences.
7
spaCy Matcher Example
import spacy
from spacy.matcher import Matcher
nlp = spacy.load('en_core_web_sm')
doc = nlp('I love NLP and machine learning')
matcher = Matcher(nlp.vocab)
pattern = [{'LOWER':'nlp'}]
matcher.add('NLP_PATTERN', [pattern])
matches = matcher(doc)
for match_id, start, end in matches:
print(doc[start:end].text)
Matches specific token patterns in text using spaCy Matcher.
8
spaCy Entity Ruler Example
import spacy
from spacy.pipeline import EntityRuler
nlp = spacy.load('en_core_web_sm')
ruler = EntityRuler(nlp)
ruler.add_patterns([{'label':'ORG','pattern':'OpenAI'}])
nlp.add_pipe(ruler, before='ner')
doc = nlp('OpenAI develops AI models.')
for ent in doc.ents:
print(ent.text, ent.label_)
Adds custom named entities using spaCy's EntityRuler.
9
spaCy Text Similarity Example
import spacy
nlp = spacy.load('en_core_web_md')
text1 = nlp('I love machine learning')
text2 = nlp('I enjoy NLP')
similarity = text1.similarity(text2)
print(similarity)
Computes similarity between two texts using spaCy vectors.
10
spaCy Custom Component Example
import spacy
nlp = spacy.load('en_core_web_sm')
def custom_component(doc):
print('Processing text:', doc.text)
return doc
nlp.add_pipe(custom_component, last=True)
doc = nlp('SpaCy pipelines are powerful.')
Adds a custom pipeline component to process text.