import spacy from spacy.matcher import Matcher nlp = spacy.load("en_core_web_sm") # Load the small English model matcher = Matcher(nlp.vocab) # Initialize the Matcher object # Define the pattern pattern = [{"LOWER": "dog"}, {"POS": "ADJ"}] # Add the pattern to the matcher matcher.add("Dog_Adj_Pattern", None, pattern) # Test the matcher on some sample text doc = nlp("I have a black dog") matches = matcher(doc) for match_id, start, end in matches: matched_text = doc[start:end].text print(matched_text)
import spacy from spacy.matcher import Matcher nlp = spacy.load("en_core_web_sm") # Load the small English model matcher = Matcher(nlp.vocab) # Initialize the Matcher object # Define the patterns pattern1 = [{"LOWER": "new"}, {"LOWER": "york"}] pattern2 = [{"LOWER": "nyc"}] pattern3 = [{"LOWER": "big"}, {"LOWER": "apple"}] # Add the patterns to the matcher matcher.add("NYC_Pattern", None, pattern1, pattern2, pattern3) # Test the matcher on some sample text doc = nlp("I love visiting NYC and exploring the Big Apple") matches = matcher(doc) for match_id, start, end in matches: matched_text = doc[start:end].text print(matched_text)Here, we use the Spacy Matcher to match a pattern of "New York", "NYC" or "Big Apple" in the text "I love visiting NYC and exploring the Big Apple". The Matcher finds two matches and prints out the matched text "NYC" and "Big Apple". Package library: SpaCy