Sub topic 3
Noun chunks and their roots
This chapter assumes you know basic Python, can install packages with pip, and can name the grammatical subject and object of a sentence. You should already have run python -m spacy download en_core_web_sm.
Noun chunks and their roots
A noun chunk is a noun phrase that works as one unit, such as "The small team." Every chunk has a root, the token the rest of the phrase depends on. Here the root of "The small team" is "team."
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The small team wrote a detailed report about the results.")
for chunk in doc.noun_chunks:
print(chunk.text, "|", chunk.root.text, chunk.root.dep_, chunk.root.head.text)Extracting subject-verb-object relations
A subject-verb-object (SVO) triple answers "who did what to whom." Find each verb's nominal subject (nsubj), then check its direct objects. The code checks both dobj and obj because label sets differ between models.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Researchers published the dataset and the editors reviewed the paper.")
for token in doc:
if token.dep_ == "nsubj" and token.head.pos_ == "VERB":
verb = token.head
objects = [c for c in verb.children if c.dep_ in ("dobj", "obj")]
for obj in objects:
print(token.text, verb.lemma_, obj.text)Matching grammatical patterns with DependencyMatcher
DependencyMatcher finds a tree shape instead of a word sequence. The > operator means the left token is the head of the right token. This pattern finds a verb that governs a subject.
import spacy
from spacy.matcher import DependencyMatcher
nlp = spacy.load("en_core_web_sm")
matcher = DependencyMatcher(nlp.vocab)
pattern = [
{"RIGHT_ID": "verb", "RIGHT_ATTRS": {"POS": "VERB"}},
{
"LEFT_ID": "verb",
"REL_OP": ">",
"RIGHT_ID": "subject",
"RIGHT_ATTRS": {"DEP": "nsubj"},
},
]
matcher.add("VERB_SUBJECT", [pattern])
doc = nlp("The engineer fixed the bug.")
for match_id, token_ids in matcher(doc):
print([doc[i].text for i in token_ids])Pipeline components, nlp.pipe, and disabling
The nlp object runs text through a sequence of components: tokenizer, tagger, parser, and named entity recognizer. Disable the components you do not need to save time. Use nlp.pipe to process many texts in batches.
import spacy
texts = ["The cat sat on the mat.", "Dogs chase balls in the park."]
nlp = spacy.load("en_core_web_sm", disable=["ner"])
print(nlp.pipe_names)
for doc in nlp.pipe(texts, batch_size=50):
print([(t.text, t.pos_, t.dep_) for t in doc])Do not disable the parser if you need dep_ or noun_chunks. Those features depend on it.
When the parser is wrong
The parser is a statistical model, so it makes mistakes. It often misattaches prepositional phrases, as in "I saw the man with the telescope," where the telescope could belong to either the man or the seeing. Informal text, unusual names, and domain jargon also cause errors.
> Check the parse before you trust an extraction.
Before relying on output, print the tokens and their heads for a few sentences from your real data and confirm that the relations are correct.
Exercise
Using the SVO code above, what does it print for the sentence "Students wrote the essays"?
Show answer
It prints "Students write essay", because "Students" is the nsubj of "wrote," whose lemma is "write," and "essays" is the dobj. The lemma of "essays" is not used, so the output shows the surface form "essays."