Articles → NLP → Phrase Matching In Spacy

Phrase Matching In Spacy






Purpose





Example


import spacy
from spacy.matcher import PhraseMatcher

# Load a small English model
nlp = spacy.load("en_core_web_sm")

# Initialize PhraseMatcher
matcher = PhraseMatcher(nlp.vocab)

# Define multi-word phrases
terms = ["New York City", "San Francisco", "machine learning"]
patterns = [nlp.make_doc(text) for text in terms]

# Add them to the matcher
matcher.add("PHRASES", patterns)

# Example text
doc = nlp("I studied machine learning in San Francisco before moving to New York City.")

# Apply matcher
matches = matcher(doc)

# Print results
for match_id, start, end in matches:
    span = doc[start:end]
    print("Matched phrase:", span.text)



Output


Picture showing the output of phrase matching in spacy



Posted By  -  Karan Gupta
 
Posted On  -  Tuesday, December 23, 2025

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250