Sub topic 10
Noun Chunks and Their Roots
This chapter assumes you can load a spaCy pipeline and read token.dep_ and token.head, as covered in the earlier chapters on dependency relations and tree navigation. You should also be comfortable with Span slicing, such as doc[2:5]. The examples use en_core_web_sm, which you install with python -m spacy download en_core_web_sm.
What a noun chunk is
A noun chunk is a "flat" noun phrase. It contains a head noun (or pronoun) plus the words that modify it from the left, such as determiners and adjectives. It does not contain other noun phrases nested inside it, and it normally stops before prepositional phrases and relative clauses.
For "the small team wrote a detailed report about the results", the chunks are "the small team", "a detailed report", and "the results". The phrase "a detailed report about the results" is a larger noun phrase, but spaCy reports only the flat pieces. The preposition "about" is left out.
Noun chunks come from the dependency parse, not from a separate model. The noun_chunks iterator applies language-specific rules to POS tags and dependency labels. Chunks are therefore only as good as the tags and labels they are built from.
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)Each line shows the chunk text, then its root token, the root's dependency label, and the head the root attaches to. With the small English model you should typically see team as nsubj of wrote, report as dobj of wrote, and results as pobj of about. Exact labels can differ between model versions.
Chunks are spans
doc.noun_chunks yields Span objects. Everything you know about spans applies: start, end, text, sent, slicing, and iteration over tokens. Chunks also have a root attribute, which is the single token the rest of the chunk depends on.
The root is not always the last token, though in English base noun phrases it usually is. It is the token whose head lies outside the chunk (or is itself, for a sentence root). Everything else in the chunk is a descendant of the root.
Two facts follow from this structure:
- The root's
dep_tells you the chunk's grammatical role in the sentence: subject, object, object of a preposition, and so on. - The root's
headtells you what the chunk attaches to. For a subject or object, that is the governing verb. Forpobj, it is the preposition.
Reading a chunk's role
Because the role lives on the root, you can classify chunks by looking at chunk.root.dep_.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The new manager approved the budget, and the board praised her.")
for chunk in doc.noun_chunks:
role = chunk.root.dep_
if role in ("nsubj", "nsubjpass"):
kind = "subject"
elif role in ("dobj", "obj"):
kind = "object"
elif role == "pobj":
kind = "prepositional object"
else:
kind = "other (" + role + ")"
print(f"{chunk.text!r:20} {kind:22} governed by {chunk.root.head.text!r}")Note that "her" is a pronoun, and pronouns appear in noun_chunks as one-token chunks. Filter on chunk.root.pos_ == "PRON" if you want only content noun phrases.
Checking both dobj and obj, and both nsubj and nsubjpass, is a habit worth keeping. Label sets differ between languages and model families. Passive sentences ("The budget was approved by the manager") label the grammatical subject nsubjpass, which is the logical object.
Cleaning chunk text
A raw chunk often includes a leading determiner ("the", "a"). That is noise if you are counting or deduplicating phrases. A common cleanup is to drop leading determiners and lemmatize the root:
import spacy
nlp = spacy.load("en_core_web_sm")
def normalized_chunk(chunk):
tokens = list(chunk)
while tokens and tokens[0].pos_ in ("DET", "PRON"):
tokens = tokens[1:]
if not tokens:
return None
words = [t.text.lower() for t in tokens[:-1]]
words.append(chunk.root.lemma_.lower() if tokens[-1] == chunk.root else tokens[-1].text.lower())
return " ".join(words)
doc = nlp("The small teams wrote several detailed reports.")
for chunk in doc.noun_chunks:
print(chunk.text, "->", normalized_chunk(chunk))The function strips leading determiners and pronouns and lemmatizes the final word only when it is the chunk root. The earlier words keep their surface form ("small", "detailed"). Lemmatizing every token would turn "detailed" into "detail", which changes the meaning.
If the chunk is only a determiner or pronoun (such as "her"), the function returns None. Handle that case before using the result.
Merging chunks into single tokens
Sometimes you want each noun phrase to behave as one token, for example before running a simple matcher. Use the retokenizer:
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The small team wrote a detailed report about the results.")
with doc.retokenize() as retokenizer:
for chunk in doc.noun_chunks:
retokenizer.merge(chunk)
print([t.text for t in doc])Merged tokens inherit the attributes of the chunk root (pos_, dep_, head). This is why merging noun chunks is a quick way to simplify a tree. Noun chunks never overlap, so merging them is safe.
Retokenizing changes the Doc in place, so token indices shift. Collect any index-based information before you merge, or work on a copy with doc.copy().
Requirements and failure modes
Noun chunks need dependency annotation. If you disable or exclude the parser, accessing doc.noun_chunks raises an error saying the chunks need the dependency parse. Check first when your pipeline is configured dynamically:
import spacy
nlp = spacy.load("en_core_web_sm", exclude=["parser"])
doc = nlp("The small team wrote a detailed report.")
if doc.has_annotation("DEP"):
print(list(doc.noun_chunks))
else:
print("No dependency parse; noun chunks are unavailable.")Other pitfalls to know about:
noun_chunksis a generator. You can loop over it once. Wrap it inlist()if you need its length or a second pass.- Coordination splits chunks. "the editors and the authors" yields two chunks. A noun joined by "and" depends on the first noun through
conj, so it becomes the root of its own chunk. If you need the whole conjoined phrase, use the subtree of the first root instead. - Chunks are not entities. "New York City Council" may be one entity and one chunk, or they may disagree about where the phrase starts and ends. Named entities come from a different component (
ner). Compare them against chunks instead of assuming they match. - Post-modifiers are excluded. "the report about the results" gives two chunks. Take
chunk.root.subtreeif you want the full phrase including prepositional attachments. The result can be much longer than you expect. - Parser errors carry through. A wrong attachment can change a root's
dep_, which shifts which chunk looks like a subject. Spot-check results on your own text before relying on role labels.
Choosing chunks or subtrees
| Need | Use | Why |
|---|---|---|
| Short, countable phrases for keywords | `doc.noun_chunks` | Flat, non-overlapping, cheap to compute |
| Grammatical role of each phrase | `chunk.root.dep_` | The root carries the label that links the chunk to the sentence |
| Full phrase with prepositional attachments | `root.subtree` or edges | Includes everything that depends on the root |
| Phrases that match real-world names | `doc.ents` | Entity recognition is a separate, trained component |
Exercises
Exercise
Write code that prints every noun chunk in a text whose root is the subject of a verb, together with that verb's lemma. Which two dependency labels should you accept, and why?
Show answer
Loop over doc.noun_chunks, test chunk.root.dep_ in ("nsubj", "nsubjpass"), and print chunk.text and chunk.root.head.lemma_. Accept nsubj for active sentences and nsubjpass for passive ones, where the grammatical subject is the logical object. You may also check chunk.root.head.pos_ in ("VERB", "AUX") so that you skip subjects whose head is not a verb.
Exercise
A text contains "the editors and the authors reviewed the paper". The code lists "the editors", "the authors", and "the paper" as separate chunks. How do you recover "the editors and the authors" as one phrase, and what does the tree tell you about why the chunks were split?
Show answer
The word "authors" depends on "editors" through a conj relation, so it is the root of its own chunk. To get the combined phrase, take the subtree of "editors", which includes the cc ("and") and the conj noun with its determiner. That is doc[root.left_edge.i : root.right_edge.i + 1] with root set to the "editors" token. The flat chunk rule splits at the conjunction because each noun is a separate head.