Sub topic 1
Loading a Pipeline and Creating a Doc
Prerequisites
You should know basic Python, including loops and installing packages with pip. You should also recognize grammar terms such as noun, verb, and subject. Install the English model once with python -m spacy download en_core_web_sm.
Loading a pipeline and creating a Doc
spacy.load reads a trained model from disk and returns an nlp object. Calling nlp on a string runs every pipeline step and returns a Doc, a container of tokens and their annotations.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The quick brown fox jumps over the lazy dog.")
print(type(doc), len(doc))Tokens and their attributes
A token is one unit of text, usually a word or a punctuation mark. Each token exposes attributes such as text, is_alpha, and lemma_. Attributes with a trailing underscore return readable strings. Attributes without it return integer codes.
for token in doc[:4]:
print(token.i, token.text, token.is_alpha)Part-of-speech tags: pos_ versus tag_
pos_ holds a coarse Universal POS tag such as NOUN, VERB, or ADJ. tag_ holds a fine-grained Penn Treebank tag such as NN (singular noun), NNS (plural noun), or VBZ (third-person singular verb). Use pos_ for broad rules and tag_ when number or tense matters.
for token in doc[:4]:
print(token.text, token.pos_, token.tag_, spacy.explain(token.tag_))Morphological features with token.morph
token.morph stores features such as number, tense, and mood as key-value pairs. Use token.morph.get("Tense") to read one feature. The result is a list such as ['Pres'], or an empty list when the feature does not apply.
for token in doc:
if token.pos_ == "VERB":
print(token.text, token.morph.get("Tense"))Exercise
Which attribute gives the coarse tag for "dogs", and which gives the fine-grained tag?
Show answer
pos gives NOUN, and tag gives NNS.