Articles → SPACY → Phrase Matching In Spacy
Phrase Matching In Spacy
Purpose
Example
import spacyfrom spacy.matcher import PhraseMatcher# Load a small English modelnlp = spacy.load("en_core_web_sm")# Initialize PhraseMatchermatcher = PhraseMatcher(nlp.vocab)# Define multi-word phrasesterms = ["New York City", "San Francisco", "machine learning"]patterns = [nlp.make_doc(text) for text in terms]# Add them to the matchermatcher.add("PHRASES", patterns)# Example textdoc = nlp("I studied machine learning in San Francisco before moving to New York City.")# Apply matchermatches = matcher(doc)# Print resultsfor match_id, start, end in matches: span = doc[start:end] print("Matched phrase:", span.text)
Output
| Posted By - | Karan Gupta |
| |
| Posted On - | Tuesday, December 23, 2025 |