Sub topic 11
Extracting subject-verb-object relations
This chapter assumes you can load a spaCy pipeline and read token.dep_, token.head, and token.children. It also assumes you know what pos_ means and can read a dependency tree. You will turn those tree links into subject-verb-object (SVO) triples, then handle the cases that break a naive version.
The working model
An SVO triple answers "who did what to whom" for one clause. In a dependency parse, the main verb is the anchor. Its subject and direct object are its children, so the extraction rule is short:
- Find a verb.
- Look at its children for a subject label and an object label.
- Report the three pieces, usually with the verb reduced to its lemma.
Here is the simplest version:
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)This should print Researchers publish dataset and editors review paper. Each triple holds single head words, not full phrases. The loop starts from the subject and walks up to its head verb, so each verb is visited once per subject.
The label names depend on the model. English pipelines such as en_core_web_sm label direct objects dobj. Models trained on Universal Dependencies annotation use obj. Checking both, as above, keeps the code portable. Run spacy.explain("dobj") to confirm what a label means.
Labels that matter for relations
| Label | Meaning | Where it appears |
|---|---|---|
| `nsubj` | Nominal subject of an active verb | Child of the verb |
| `nsubjpass` | Subject of a passive verb (the thing acted on) | Child of the verb |
| `dobj` / `obj` | Direct object | Child of the verb |
| `agent` | The "by" word in a passive clause | Child of the verb |
| `pobj` | Object of a preposition | Child of the preposition or agent |
| `conj` | A coordinated word ("and", "or") | Child of the first conjunct |
| `neg` | Negation such as "not" | Child of the verb or auxiliary |
The table shows why the simple extractor is fragile. Real sentences spread the meaning across several of these labels.
From head words to phrases
A triple of single words loses information. "The new budget" reduces to budget. A common fix is to map each head token to the noun chunk that contains it. You build the map once per document:
chunk_of = {tok.i: chunk for chunk in doc.noun_chunks for tok in chunk}Then a helper returns the chunk text when the token sits inside a chunk, and the token text otherwise. Verbs and some pronouns or proper nouns may fall outside a chunk, so the fallback matters.
Using token.subtree is the other option. It gives the full phrase, but it also pulls in relative clauses, appositions, and conjuncts. For "the editor who left the meeting", the subtree of editor includes the whole relative clause. Noun chunks are shorter and more predictable.
A more complete extractor
The function below adds four things to the simple version. It handles verbs coordinated with "and", subjects and objects joined by "and", passive voice, and negation.
import spacy
nlp = spacy.load("en_core_web_sm")
def extract_svo(doc):
chunk_of = {tok.i: chunk for chunk in doc.noun_chunks for tok in chunk}
def phrase(token):
chunk = chunk_of.get(token.i)
return chunk.text if chunk is not None else token.text
def expand(token):
return [token, *token.conjuncts]
def find_subjects(verb):
subjects = [c for c in verb.children if c.dep_ in ("nsubj", "nsubjpass")]
if not subjects and verb.dep_ == "conj":
return find_subjects(verb.head)
return subjects
triples = []
for verb in doc:
if verb.pos_ != "VERB":
continue
negated = any(c.dep_ == "neg" for c in verb.children)
objects = [c for c in verb.children if c.dep_ in ("dobj", "obj")]
for subj in find_subjects(verb):
if subj.dep_ == "nsubjpass":
agents = [
g
for a in verb.children
if a.dep_ == "agent"
for g in a.children
if g.dep_ == "pobj"
]
pairs = [(a, subj) for a in agents]
else:
pairs = [(subj, o) for o in objects]
for left, right in pairs:
for s in expand(left):
for o in expand(right):
triples.append((phrase(s), verb.lemma_, phrase(o), negated))
return triples
sentences = [
"The committee approved the new budget.",
"The paper was reviewed by the editors.",
"Alice writes and edits reports.",
"The team did not accept the proposal.",
]
for doc in nlp.pipe(sentences):
print(doc.text)
for triple in extract_svo(doc):
print(" ", triple)With a typical en_core_web_sm model you can expect these results:
- The first sentence gives
("The committee", "approve", "the new budget", False). - The passive sentence gives
("the editors", "review", "The paper", False). The logical subject is theagent'spobj, and the grammatical subject becomes the object. - "Alice writes and edits reports" gives two triples.
editsis aconjofwritesand has no subject of its own, sofind_subjectsborrowsAlicefrom the head verb. - The last sentence gives a triple with
negatedset toTrue. Thenegchild hangs off the verbaccept, not off the auxiliarydid. A parser may attach it elsewhere in other constructions, so test this on your own data.
Exact output depends on the model version. Statistical parsers change between releases, so treat these as expectations, not guarantees.
How the algorithm flows
Common errors
Missing the verb because of AUX. The check pos_ == "VERB" skips copular sentences like "The report is late". There the head is is, tagged AUX, and the predicate is an adjective (acomp) or noun (attr). If you need copular relations, add a separate rule for them. Do not widen the verb test to include every auxiliary, because "has been reviewing" would then produce triples for has and been too.
Missing prepositional objects. "The team relied on the report" has no dobj. The report is the pobj of the preposition on, which is a child of relied. A subject-verb-preposition-object extractor needs one more hop: for each child with dep_ == "prep", read its pobj children and keep the preposition as part of the relation name.
Open clausal complements. In "She wants to leave the company", leave is an xcomp of wants. It has no subject child. The subject belongs to wants. The conj fallback in the code does not cover this, so add a similar rule for xcomp if you need it.
Pronouns and coreference. A triple like ("It", "approve", "the budget") is correct from the parse but useless on its own. spaCy's core pipeline does not resolve pronouns, so you must filter them (token.pos_ == "PRON") or add a coreference component.
Wrong parses. Attachment errors propagate straight into triples. A prepositional phrase attached to the wrong word, or a noun mislabeled as a verb, produces a wrong or missing triple with no warning.
Design choices
- Single head words or noun chunks. Head words are easy to count and deduplicate. Chunks are easier for humans to read. Many pipelines store both.
- Lemma or surface form for the verb. Lemmas let "approved", "approves", and "approving" count as one relation. Keep tense information elsewhere (
token.morph) if it matters. - Rules or matcher. Hand-written loops are easy to step through and extend, as above.
DependencyMatcherexpresses a fixed pattern declaratively, but it handles passives, conjunct subject inheritance, and negation less naturally. Use the loop approach until your patterns stabilize. - Recall or precision. Each added rule (conjuncts,
xcomp, prepositions) raises recall and adds a new way to be wrong. Add rules one at a time and measure on labeled examples.
Exercise
Why does the sentence "The proposal was rejected by the board." return no triple from a loop that only looks for children labeled nsubj and dobj, and what two changes would produce the triple ("the board", "reject", "The proposal")?
Show answer
The passive subject is labeled nsubjpass, not nsubj, and the verb has no dobj child. The doer appears as a pobj under an agent child. The first change is to accept nsubjpass as a subject label. The second change is, when a subject is nsubjpass, to read the pobj under the verb's agent child as the logical subject and use the passive subject as the object. The verb lemma reject comes from verb.lemma_.
Exercise
Extend extract_svo so that for each verb it also emits relations of the form (subject, "relied on", object) for prepositional objects. Which tokens do you inspect, and which attribute lets you build the relation name?
Show answer
For each verb, loop over its children with dep_ == "prep". For each such preposition, loop over its children with dep_ == "pobj". Build the relation name as verb.lemma_ + " " + prep.text, for example rely on. Pair it with the verb's subjects, expanding conjuncts and mapping tokens to noun chunks as before.