Sub topic 3
The spaCy Pipeline, Doc and Span
This chapter assumes basic Python, familiarity with tokens and text processing, and a general idea of how a neural-network classifier works. You will use an installed spaCy language model, such as en_core_web_sm.
How a spaCy pipeline works
A spaCy pipeline turns raw text into a Doc object. A Doc is spaCy's structured representation of text. It contains tokens, sentence information, and annotations created by pipeline components.
The pipeline usually runs in this order:
- The tokenizer splits text into tokens.
- Components process the tokens.
- Components add annotations such as part-of-speech tags, dependencies, and named entities.
The nlp object represents the complete pipeline. Calling nlp(text) tokenizes the text and runs every enabled component.
You can inspect which components are active:
import spacy
nlp = spacy.load("en_core_web_sm")
print(nlp.pipe_names)The exact list depends on the model. A small English model commonly includes components named tok2vec, tagger, parser, attribute_ruler, lemmatizer, and ner.
A component receives a Doc, changes or adds annotations, and returns the Doc. This shared object lets later components use earlier results.
The Doc, Token, and Span objects
A Doc behaves partly like a sequence of tokens. Each item is a Token object. A token has text and linguistic attributes:
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("Apple opened an office in London.")
for token in doc:
print(token.text, token.pos_, token.lemma_)token.text is the original token text. token.pos_ is the part-of-speech label. token.lemma_ is the base form, when the model provides one.
A Span is a contiguous view of several tokens. You create one with a start index and an exclusive end index:
location = doc[5:6]
print(location.text)The span contains token positions 5 through, but not including, position 6. It also preserves its position in the original document through start and end.
Named entities are stored as spans in doc.ents. Each entity span has text, character offsets, and a label:
for entity in doc.ents:
print(
entity.text,
entity.start,
entity.end,
entity.start_char,
entity.end_char,
entity.label_,
)Token offsets count tokens. Character offsets count characters in the original string. Character offsets are useful when you need to highlight an entity or connect it to an external annotation.
Reading and creating annotations
The named entity recognizer adds spans to doc.ents. You can convert them into ordinary records for later processing:
entities = [
{
"text": entity.text,
"label": entity.label_,
"start": entity.start_char,
"end": entity.end_char,
}
for entity in doc.ents
]
print(entities)A Span is tied to its source Doc. This means a span is not an independent copy of the text. Keep the original document available while using the span.
Adding a custom pipeline component
You can add your own component when you need to inspect or modify a Doc. A component must accept a Doc and return it.
import spacy
from spacy.language import Language
@Language.component("report_length")
def report_length(doc):
doc.user_data["character_count"] = len(doc.text)
return doc
nlp = spacy.load("en_core_web_sm")
nlp.add_pipe("report_length", last=True)
doc = nlp("A short example.")
print(doc.user_data["character_count"])Use nlp.pipe() when processing many texts. It batches work more efficiently than repeatedly calling nlp in a loop:
texts = ["Apple is in California.", "London is in the United Kingdom."]
for doc in nlp.pipe(texts):
print([(entity.text, entity.label_) for entity in doc.ents])Exercise
What is the difference between a Token and a Span, and where does spaCy store named entity spans?
Show answer
A Token represents one token, while a Span represents a contiguous range of tokens. spaCy stores recognized named entity spans in the document's doc.ents collection.