Sub topic 7
Sentence boundaries from the parse
This chapter assumes you can load a pipeline, read token attributes, and read dep_ and head as covered in earlier chapters. It explains where doc.sents comes from, how to check and control it, and what goes wrong when boundaries are missing or misplaced.
Where sentences come from
A spaCy Doc has no sentence list built in. Boundaries are stored as a per-token flag, token.is_sent_start, and some pipeline component must set it. In en_core_web_sm the dependency parser sets it. The parser builds one tree per sentence, so deciding where each tree starts and ends gives you the boundaries for free.
doc.sents then reads those flags and yields one Span per sentence. It is a generator, not a list.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The committee approved the budget. Then it adjourned. Did anyone object?")
for i, sent in enumerate(doc.sents):
print(i, repr(sent.text), "| root:", sent.root.text, "| tokens:", len(sent))Each sentence span has a root, the single token whose head is itself. This follows from the parser producing one tree per sentence. A head never points outside its own sentence.
Reading the boundary flags
You can inspect the flags directly. is_sent_start is True for the first token of a sentence, False for other tokens, and None when no component has decided. is_sent_end is the mirror image. token.sent returns the sentence span that contains the token.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Birds sing. Cats listen.")
for token in doc:
print(token.i, token.text, token.is_sent_start, token.is_sent_end, "->", token.sent.text)Three practical facts follow from this model:
token.iis an index into the wholeDoc, not into the sentence. Usesent.startandsent.endto convert between them.len(sent)counts tokens, not characters.sent.as_doc()copies a sentence into a newDoc. Use it when downstream code expects a full document.
Checking that boundaries exist
If no component has set boundaries, doc.sents raises a ValueError. This catches people who build a blank pipeline, or who disable the parser to save time.
import spacy
nlp = spacy.blank("en")
doc = nlp("One sentence. Another sentence.")
print(doc.has_annotation("SENT_START"))
try:
print(list(doc.sents))
except ValueError as err:
print("No boundaries:", str(err)[:60])doc.has_annotation("SENT_START") is the safe test. Call it before iterating if the pipeline configuration is not under your control.
Because doc.sents is a generator, len(doc.sents) fails with a TypeError. Convert it first:
sentences = list(doc.sents)
print(len(sentences))Three components that set boundaries
spaCy offers three ways to produce boundaries. They differ in what they need and how they decide.
| Component | Method | Needs a trained model | Gives dependencies | Typical use |
|---|---|---|---|---|
| `parser` | Statistical, decided jointly with the tree | Yes | Yes | Default. Best accuracy on messy text when you also need `dep_` |
| `senter` | Statistical, boundaries only | Yes | No | Faster than the parser when you need sentences but not the tree |
| `sentencizer` | Rules on punctuation tokens | No | No | Blank pipelines, clean text, maximum speed |
The senter
Trained English pipelines ship a senter that is disabled by default. To use it without paying for the parser, exclude the parser and enable the senter.
import spacy
nlp = spacy.load("en_core_web_sm", exclude=["parser"])
nlp.enable_pipe("senter")
print(nlp.pipe_names)
doc = nlp("The senter finds boundaries. It builds no tree.")
print([s.text for s in doc.sents])
print(doc[1].dep_ == "")The last line prints True because no component set dependency labels. Excluding the parser removes the tree as well as the boundaries, so any code that reads dep_, head, or noun_chunks will fail or return empty results.
The sentencizer
The sentencizer is a rule-based component. It starts a new sentence after a token that is a sentence-ending punctuation mark (by default ., !, ? and a few others from other scripts). It works in a blank pipeline.
import spacy
nlp = spacy.blank("en")
nlp.add_pipe("sentencizer")
doc = nlp("It is fast. It is simple! Is it accurate?")
print([s.text for s in doc.sents])Because it looks only at punctuation tokens, it cannot use context. It can split inside a quoted exclamation or a name that ends in punctuation. It also finds no boundary in text without punctuation.
Comparing them on your own data
Run the same text through each and compare counts. Differences point to the sentences worth reading by hand.
import spacy
text = "Dr. Lee asked a question. Nobody answered. the meeting went on and on"
parser_nlp = spacy.load("en_core_web_sm")
rule_nlp = spacy.blank("en")
rule_nlp.add_pipe("sentencizer")
for name, pipeline in [("parser", parser_nlp), ("sentencizer", rule_nlp)]:
doc = pipeline(text)
print(name, len(list(doc.sents)))
for sent in doc.sents:
print(" ", sent.text)Controlling boundaries yourself
The parser respects boundaries that are already set when it runs. This lets you inject your own rule, for example splitting at semicolons, and still get a consistent parse for each piece. The custom component must run before the parser.
import spacy
from spacy.language import Language
@Language.component("semicolon_boundaries")
def semicolon_boundaries(doc):
for token in doc[:-1]:
if token.text == ";":
doc[token.i + 1].is_sent_start = True
return doc
nlp = spacy.load("en_core_web_sm")
nlp.add_pipe("semicolon_boundaries", before="parser")
doc = nlp("The server restarted; the logs were cleared; nobody noticed.")
for sent in doc.sents:
print(repr(sent.text), "| root:", sent.root.text)Note the loop over doc[:-1]. It avoids indexing past the end when the last token is a semicolon.
Rules for setting is_sent_start by hand:
- Set it to
Trueto force a boundary. Set it toFalseto forbid one. - Do it only before the parser (or senter) runs. Writing to
is_sent_starton a document that is already parsed raises an error. - Setting only some tokens is fine. The parser fills in the rest.
Failure modes
Sentence segmentation errors are common, and they spread. A wrong boundary changes the tree, the root, and every extraction that works per sentence.
- Missing punctuation. Chat messages, subtitles, and headlines often lack final periods. The parser may merge several sentences into one tree with a strange root.
- Line-based text. Bulleted lists and tables where each line is a unit but no punctuation ends it. Add a custom component that marks line starts, or split the text yourself and run
nlp.pipeon the pieces. - Abbreviations and decimals. The tokenizer handles many of them (such as
Dr.), but domain terms and unusual abbreviations can still trigger false boundaries in either the rules or the statistical models. - Very long sentences. Legal or scraped text may contain run-on sentences with hundreds of tokens. Parse quality drops with length, and one long sentence can dominate a batch's processing time.
- Disabled components. Excluding the parser silently removes sentences unless another component replaces it.
Exercises
Exercise
You load en_core_web_sm with exclude=["parser"] and do not enable any other sentence component. What happens when you run list(doc.sents), and which two ways could you fix it?
Show answer
It raises a ValueError because no component has set sentence boundaries, and doc.has_annotation("SENT_START") is False. You can fix it by calling nlp.enable_pipe("senter") (statistical boundaries without a tree) or by adding nlp.add_pipe("sentencizer") (rule-based boundaries on punctuation).
Exercise
Write the body of a component that forces a new sentence after every token whose text is "--", and say where in the pipeline it must be added for the parser to respect it.
Show answer
Loop over doc[:-1]. For each token with token.text == "--", set doc[token.i + 1].is_sent_start = True, then return doc. Register it with @Language.component(...) and add it with nlp.add_pipe(name, before="parser"), so that the boundaries exist before the parser runs. Setting them after parsing raises an error.