SpaCy & Semantic Mappings
2025-11-05
import spacy
import pandas as pd
# Load English model
nlp = spacy.load("en_core_web_sm")
text = "Dr. Byrd's students can't wait to analyze PIE roots!"
doc = nlp(text)
# Create list of dicts, one per token
data = []
for t in doc:
data.append({
"text": t.text,
"lemma": t.lemma_,
"POS": t.pos_,
"tag": t.tag_,
"stop": t.is_stop,
"is_punct": t.is_punct
})
# Make DataFrame
df = pd.DataFrame(data)
print(df)alice.txt. Make sure it’s in the same folder as this .qmd file.pd.DataFrame, and count how many times each word occurs in the story.import spacy
import pandas as pd
# Load English model
nlp = spacy.load("en_core_web_sm")
text2 = "President Pitzer, Mr. Vice President, Governor Connally, ladies and gentlemen: I am delighted to be here today. We meet in an hour of change and challenge."
doc2 = nlp(text2)
[s.text for s in doc2.sents]displaCy.children attribute, we identify all immediate syntactic dependents of a tokenimport spacy
nlp = spacy.load("en_core_web_sm")
# Step 1: Our manual list of violent verbs
verbs_of_violence = ["attack", "hit", "kick", "strike", "punch", "assault", "kill", "hurt"]
# Step 2: Process a sentence
doc = nlp("They punched, kicked, and attacked the intruder before fleeing.")
# Step 3: Find any tokens whose lemma is in our list
matches = [(t.text, t.lemma_) for t in doc if t.lemma_ in verbs_of_violence]
print(matches)How might we narrow down these words by function & semantic class?
nlp()obj_dep = ["dobj", "pobj", "obj"]obj_deps to a list objectsmatches, as we did above:import spacy
nlp = spacy.load("en_core_web_sm")
# Step 1: Define your semantic group
dog_words = ["dog", "hound", "terrier", "poodle", "retriever", "shepherd", "beagle", "collie"]
# Step 2: Sample text
text = "The farmer owned three terriers, but the poodle ran away with a collie."
# Step 3: Process the text
doc = nlp(text)
# Step 4: Collect all nouns that are objects of verbs or prepositions
obj_deps = ["dobj", "pobj", "obj"]
objects = []
for tok in doc:
if tok.dep_ in obj_deps:
objects.append(tok)
# Step 5: Keep only those whose lemma is in our semantic group
matches = [(t.text, t.lemma_) for t in objects if t.lemma_.lower() in dog_words]
print(matches)verbs_of_violence and dog_wordsdoc = nlp("The dog chased the cat.")
tok = doc[1]
synsets = tok._.wordnet.synsets() # list of NLTK-style Synset objects
print(f"These are the different meanings the word '{tok}' has:")
count = 0
for i in synsets:
print(f"{count}: ", i)
count += 1doc = nlp("The dog chased the cat.")
tok = doc[2]
for s in tok._.wordnet.synsets():
print(s, "→", s.definition())import spacy
from nltk.corpus import wordnet as wn
from nltk.corpus.reader.wordnet import NOUN, VERB, ADJ, ADV
# Load spaCy
nlp = spacy.load("en_core_web_sm")
# Sentence with both noun and verb "bear"
text = "The bears bear their burdens bravely."
doc = nlp(text)
# Map spaCy POS tags to WordNet POS tags -- this is a **function**, we'll get to these soon
def get_wordnet_pos(spacy_pos):
if spacy_pos.startswith("N"):
return NOUN
elif spacy_pos.startswith("V"):
return VERB
elif spacy_pos.startswith("J"):
return ADJ
elif spacy_pos.startswith("R"):
return ADV
return None
# Loop through tokens and look up WordNet entries
for token in doc:
wn_pos = get_wordnet_pos(token.tag_)
lemma = token.lemma_.lower()
if wn_pos and not token.is_stop and not token.is_punct:
synsets = wn.synsets(lemma, pos=wn_pos)
print(f"\n{token.text.upper()} ({token.pos_}) → lemma: {lemma}")
for s in synsets[:3]: # show just the first 3 senses
print(f" - {s.definition()} [examples: {s.examples()}]")Using previous code as a model: