Sub topic 4
Morphological Features with token.morph
This chapter assumes you can load a spaCy pipeline and read pos_ and tag_. You should also know basic grammar terms such as noun, verb, singular and plural. The chapter covers what token.morph stores, how to query it, and where it comes from. It also covers the mistakes that tend to appear when you rely on it.
What morphology adds
A part-of-speech tag says a token is a verb or a noun. It does not say whether the verb is past or present tense, or whether the noun is singular or plural. Morphology is the part of grammar concerned with these word-form details. In spaCy, each token carries a morphological analysis in token.morph.
The analysis is a set of feature-value pairs in the Universal Dependencies style. Examples are Number=Plur, Tense=Past and VerbForm=Fin. Printing it gives one string with pairs joined by |.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The dogs barked loudly, and she walked home.")
for token in doc:
print(f"{token.text:<8} {token.pos_:<6} {token.tag_:<5} {str(token.morph)!r}")Typical output for the verbs and the noun:
dogshasNumber=Plur.barkedhasAspect=Perf|Tense=Past|VerbForm=PartorTense=Past|VerbForm=Fin, depending on how the model reads it.loudlyusually has an empty string, because adverbs carry few features in English.
An empty morph is normal. Many tokens, such as punctuation and conjunctions, have no features. Do not treat an empty string as an error.
The MorphAnalysis object
token.morph is not a plain string. It is a MorphAnalysis object, and three methods cover most uses:
str(token.morph)returns the pipe-separated string.token.morph.get("Tense")returns a list of values for one feature. The list is empty if the feature is absent.token.morph.to_dict()returns a dictionary mapping each feature to its value.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("She was reading three books.")
for token in doc:
morph = token.morph
print(token.text)
print(" string:", str(morph))
print(" dict: ", morph.to_dict())
print(" Number:", morph.get("Number"))
print(" Tense: ", morph.get("Tense"))get returns a list because a feature can in principle hold several values, as in Gender=Fem,Masc in some languages. For English you will mostly see lists of length 0 or 1. Write code that handles both cases, for example values[0] if values else None.
Use get rather than string searching. A test like "Past" in str(token.morph) can match the wrong feature. In Universal Dependencies, Tense=Past and Aspect=Perf are separate features, and a substring match ignores that structure.
Where the values come from
The source of the morphology depends on the pipeline, and this affects both accuracy and what you can change.
In the English pipelines, the tagger predicts the fine-grained tag_, such as NNS or VBD. A rule-based component called attribute_ruler then maps each tag to a coarse pos_ and to a set of morphological features. The mapping is a table, so the same tag always yields the same features.
Pipelines for several other languages, including German and Spanish, use a trained morphologizer component. It predicts pos_ and the full morphological string together, so the features can depend on context.
You can check which approach your pipeline uses:
import spacy
nlp = spacy.load("en_core_web_sm")
print(nlp.pipe_names)
print("morphologizer" in nlp.pipe_names)
print("attribute_ruler" in nlp.pipe_names)There are two practical consequences. First, in English the morph is only as good as the tag. If the tagger mislabels VBD as VBN, the morph changes with it. Second, the English table can only express features that follow from the tag. It cannot express agreement details that need wider context.
Common features and values
The table lists features you will meet most often in English. Other languages use more, such as Case and Gender.
| Feature | Applies to | Example values | Example |
|---|---|---|---|
| `Number` | nouns, pronouns, determiners | `Sing`, `Plur` | dogs: `Plur` |
| `Tense` | verbs | `Past`, `Pres` | walked: `Past` |
| `VerbForm` | verbs | `Fin`, `Inf`, `Part`, `Ger` | reading: `Part` |
| `Person` | verbs, pronouns | `1`, `2`, `3` | she: `3` |
| `Degree` | adjectives, adverbs | `Pos`, `Cmp`, `Sup` | bigger: `Cmp` |
| `PronType` | pronouns, determiners | `Prs`, `Dem`, `Int` | this: `Dem` |
Use spacy.explain for tag and dependency labels. It does not describe feature-value pairs. For those, consult the Universal Dependencies feature documentation.
Querying morphology across a text
The features become useful when you aggregate them. This example counts the tenses of finite verbs in a short passage.
from collections import Counter
import spacy
nlp = spacy.load("en_core_web_sm")
text = (
"The team released the update yesterday. "
"Users report fewer crashes, and the developers plan another release."
)
doc = nlp(text)
tenses = Counter()
for token in doc:
if token.pos_ == "VERB" and "Fin" in token.morph.get("VerbForm"):
tense = token.morph.get("Tense")
tenses[tense[0] if tense else "None"] += 1
print(tenses)The check on VerbForm=Fin excludes participles and infinitives, which would otherwise be counted as tenses they do not express. Each token is tested with get first, so a verb with no Tense value does not raise an error.
The next example finds plural nouns and returns their singular lemmas, which combines this chapter with lemmatization.
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The engineers tested the prototypes and fixed several bugs.")
plural_nouns = [
(t.text, t.lemma_)
for t in doc
if t.pos_ == "NOUN" and t.morph.get("Number") == ["Plur"]
]
print(plural_nouns)The comparison get("Number") == ["Plur"] works because get returns a list. Comparing it to the bare string "Plur" would always be false.
Matching on morphology
The rule-based Matcher can filter on the MORPH attribute. This lets you describe a pattern such as "a past-tense verb" without a Python loop.
import spacy
from spacy.matcher import Matcher
nlp = spacy.load("en_core_web_sm")
matcher = Matcher(nlp.vocab)
pattern = [{"POS": "VERB", "MORPH": {"IS_SUPERSET": ["Tense=Past"]}}]
matcher.add("PAST_VERB", [pattern])
doc = nlp("The committee approved the plan and the manager signed it.")
for match_id, start, end in matcher(doc):
print(doc[start:end].text)IS_SUPERSET means the token's morph must contain at least the listed pairs. It may contain others. Use IS_SUBSET when the token's features must all appear in your list, and INTERSECTS when any one match is enough. Exact string equality on the whole morph is fragile, because the order and set of features can differ between model versions.
Edge cases and common errors
Several habits cause most bugs with token.morph:
- Treating an empty morph as missing data. Tokens such as punctuation, conjunctions and many adverbs legitimately have no features. Filter by
pos_first. - Comparing against a string.
token.morph == "Number=Plur"does not do what you expect. Useget,to_dictorstr. - Reading a single value without checking the list.
token.morph.get("Tense")[0]raisesIndexErrorwhen the feature is absent. - Assuming feature sets are the same across languages. English has no grammatical case on nouns, so
Caseis mostly empty. German pipelines use it heavily. - Assuming stable string order. Features in the string are sorted by name, so you can rely on that within a version. Still, query by feature rather than by position.
- Ambiguous forms. A word like
readis present or past, andsawmay be a noun or a past-tense verb. The tagger decides from context and sometimes decides wrongly, and the morph follows the decision.
You can inspect an ambiguous case directly:
import spacy
nlp = spacy.load("en_core_web_sm")
for sentence in ["They read the report yesterday.", "They read reports every day."]:
doc = nlp(sentence)
token = doc[1]
print(token.text, token.tag_, token.morph.to_dict())If both sentences give the same tense, the model has not used the time word to disambiguate. Small models do this often. Treat the result as a prediction, not a fact.
Choosing between pos_, tag_, and morph
Use pos_ when you need a broad category, such as selecting nouns or verbs. Use tag_ when you need distinctions the tag set encodes in a single label, and accept that its inventory is specific to the model's training data. Use morph when you need a specific grammatical property that you want to name, such as plural number or past tense, and when you may later switch to a different language or model. The Universal Dependencies feature names stay consistent across languages, while tag sets do not.
Exercise
A colleague writes if token.morph == "Tense=Past": to find past-tense verbs, and it matches nothing. Give two reasons it fails and write a corrected condition.
Show answer
First, token.morph is a MorphAnalysis object, not a string, so it never equals a plain string. Second, a past-tense verb usually carries other features as well, such as VerbForm=Fin, so even the string form would not be exactly Tense=Past. A corrected condition is token.pos_ == "VERB" and "Past" in token.morph.get("Tense"). A Matcher pattern with "MORPH": {"IS_SUPERSET": ["Tense=Past"]} also works.
Exercise
Write a short loop that prints each token whose Number feature is Plur, together with its pos_. Explain why get is used rather than checking the string.
Show answer
for t in doc: if "Plur" in t.morph.get("Number"): print(t.text, t.pos_). get returns a list of values for exactly one feature, so the test cannot accidentally match another feature whose text contains the same characters, and it returns an empty list when the feature is absent instead of raising an error.