Sub topic 10
Lemmatisation with a lexicon
This chapter assumes you can write basic Python and regular expressions, and that you know the earlier chapters' terms: token, type, inflection, derivation, stem and lemma. It also assumes you know basic English grammar terms. You will see how a lexicon-based lemmatiser works internally, use NLTK's WordNet lemmatiser, and learn where it fails.
What a lemmatiser promises
A lemma is the dictionary headword for a group of inflected forms. The forms "runs", "ran" and "running" share the lemma "run". A stemmer cuts suffixes by rule and may return a non-word such as "studi". A lemmatiser returns a real word, because it checks its answer against a lexicon. A lexicon is a structured word list that records which words exist and how irregular forms map to base forms.
The result is cleaner, but it costs more. You need the lexicon data, you often need part-of-speech information, and you must decide what to do with words the lexicon does not contain.
How a lexicon lemmatiser works
Lexicon lemmatisers combine two resources: a table of irregular forms and a set of suffix rules. The suffix rules are only trusted when their output appears in the lexicon.
NLTK's WordNetLemmatizer calls a function named morphy from the WordNet lexicon. For a given word and part of speech, it follows these steps:
- Look the word up in the exception list for that part of speech. Entries such as "geese → goose" and "was → be" live here. If found, return the listed lemma.
- Otherwise, apply each detachment rule for that part of speech and collect the candidates.
- Keep only the candidates that exist in the lexicon as that part of speech.
- Return a surviving candidate. If none survive, return the original word unchanged.
The suffix rules are small. For nouns, WordNet uses rules such as these:
| Ending | Replaced by | Example |
|---|---|---|
| s | (nothing) | cats → cat |
| ses | s | buses → bus |
| ches | ch | churches → church |
| ies | y | studies → study |
| men | man | women → woman |
For verbs, the rules strip "s", "es", "ed" and "ing", sometimes restoring a final "e". Adjectives have rules for "er" and "est".
The lexicon check is what separates this from stemming. The noun rule for "ies" would turn "series" into "sery". Because "sery" is not in the lexicon, the candidate is rejected. WordNet also lists "series" as a noun, so the lemma stays "series".
Using the WordNet lemmatiser
The spine example shows the core behaviour, including the part-of-speech default:
import nltk
from nltk.stem import WordNetLemmatizer
nltk.download("wordnet")
lemmatizer = WordNetLemmatizer()
print(lemmatizer.lemmatize("studies"))
print(lemmatizer.lemmatize("running"))
print(lemmatizer.lemmatize("running", pos="v"))
print(lemmatizer.lemmatize("better", pos="a"))This prints study, running, run and good. The second line is the one that surprises people. Unless you pass pos, the lemmatiser treats every word as a noun. As a noun, "running" is already a valid base form, so nothing changes. The last line shows an exception-list entry: "better" is listed as an irregular comparative of "good", and no suffix rule could produce that.
The pos argument accepts four WordNet tags:
| Tag | Meaning |
|---|---|
| `"n"` | noun (default) |
| `"v"` | verb |
| `"a"` | adjective |
| `"r"` | adverb |
Other values raise an error. Penn Treebank tags such as VBG must be converted first. The next chapter covers why part of speech matters. Here you only need to know that the lemmatiser will not infer it for you.
Checking whether the lexicon knew the word
lemmatize returns the input unchanged for words it cannot resolve. That behaviour is correct for "running" as a noun, and wrong for a word like "blorbs". The two cases look the same in the output. You can tell them apart by asking WordNet whether the returned lemma exists:
import nltk
from nltk.corpus import wordnet as wn
from nltk.stem import WordNetLemmatizer
nltk.download("wordnet")
lemmatizer = WordNetLemmatizer()
def lemma_report(word, pos):
lemma = lemmatizer.lemmatize(word, pos=pos)
known = bool(wn.synsets(lemma, pos=pos))
return lemma, known
for word, pos in [("geese", "n"), ("mice", "n"), ("was", "v"), ("blorbs", "n")]:
lemma, known = lemma_report(word, pos)
print(f"{word:8} {pos} -> {lemma:8} in lexicon: {known}")Expected output:
geese n -> goose in lexicon: True
mice n -> mouse in lexicon: True
was v -> be in lexicon: True
blorbs n -> blorbs in lexicon: FalseCounting the False results across a corpus gives you a cheap coverage measure. If 15% of your tokens are unknown, the lemmatiser is doing little for that corpus.
Wiring in part of speech
In a real pipeline you tag each token first, then convert the tag to a WordNet tag. The converter below maps by the first letter of the Penn Treebank tag:
import re
import nltk
from nltk.stem import WordNetLemmatizer
for resource in ["wordnet", "averaged_perceptron_tagger",
"averaged_perceptron_tagger_eng"]:
nltk.download(resource, quiet=True)
lemmatizer = WordNetLemmatizer()
def to_wordnet_pos(penn_tag):
if penn_tag.startswith("J"):
return "a"
if penn_tag.startswith("V"):
return "v"
if penn_tag.startswith("R"):
return "r"
return "n"
def lemmatise(text):
tokens = re.findall(r"\w+", text.lower())
tagged = nltk.pos_tag(tokens)
return [lemmatizer.lemmatize(tok, pos=to_wordnet_pos(tag))
for tok, tag in tagged]
print(lemmatise("The mice were running home"))With a correct tagging, the output is ['the', 'mouse', 'be', 'run', 'home']. The tagger is statistical, so on other sentences its output can differ. A wrong tag produces a wrong or unchanged lemma. For example, if "left" is tagged as a noun, it stays "left"; as a verb it becomes "leave".
Two details in this code are worth noting. The nltk.download loop lists two tagger names because the resource name changed between NLTK versions, and a download call for a name your version does not have only reports a failure. Lower-casing happens before tagging, which helps the lemmatiser (see the next section) but can hurt the tagger, since capitalisation signals proper nouns.
Edge cases and failure modes
Case sensitivity. WordNet entries are lower case, so a capitalised form at the start of a sentence may not match. Case-fold before lemmatising unless you need to keep proper nouns apart. The trade-off is that "Apple" the company and "apple" the fruit merge.
Lexicon coverage. WordNet covers general English. It lacks most slang, brand names, technical jargon, misspellings and new words. Those tokens pass through unchanged, which is safe but inconsistent: "tweets" may reduce to "tweet" while a newer term keeps its plural.
Ambiguous forms. Some forms map to several lemmas depending on context. "Saw" is the past of "see" as a verb and the tool "saw" as a noun. "Left" is the past of "leave" or a direction. A lemmatiser given only the word cannot choose. Only context, through the POS tag, can.
Multiple candidates. When several suffix rules yield valid lexicon entries, NLTK returns the shortest. This is a heuristic, and it is usually right, but it is not a linguistic guarantee.
Derivation is untouched. Lemmatisation undoes inflection, not derivation. "Happiness" does not become "happy", and "organisation" does not become "organise". If you need derivational links, you want a stemmer, or WordNet's derivationally related forms, not a lemmatiser.
Speed. Lemmatising needs a dictionary lookup per candidate, plus a tagger pass. It is slower than the Porter stemmer. For millions of tokens, cache results per (word, pos) pair, because natural-language text repeats the same pairs constantly.
Beyond NLTK
Other toolkits package the same idea differently. spaCy's English pipeline predicts part of speech first and then applies rule tables and lookup tables to produce token.lemma_. Its lemma quality depends on the tagger in the same way. Morphological analysers for languages with rich inflection, such as Finnish or Turkish, work from finite-state transducers, which are compiled machines encoding thousands of rules plus a lexicon. The idea is the same: rules propose, a lexicon disposes.
Lemmatisation compared with stemming
| Property | Stemming (Porter, Snowball) | Lexicon lemmatisation |
|---|---|---|
| Output | Stem, may be a non-word ("studi") | Valid dictionary word ("study") |
| Irregular forms | Not handled ("geese" stays "geese") | Handled by the exception list |
| Needs part of speech | No | Yes, for best results |
| Needs a lexicon | No | Yes |
| Unknown words | Still stripped by rule | Passed through unchanged |
| Speed | Very fast | Slower |
| Typical use | Search recall, quick baselines | Readable output, linguistic analysis |
The choice between them depends on the task, and the final chapter of this tutorial covers it in detail.
Exercise
You run WordNetLemmatizer().lemmatize("was") and get was back. A colleague says the lemmatiser is broken because "was" should become "be". What is the cause, and what is the fix?
Show answer
The default part of speech is noun, and "was" has no noun entry or noun suffix rule that leads to "be". The exception list that maps "was" to "be" applies to verbs. The fix is lemmatize("was", pos="v"), which returns "be". In a pipeline, you should tag each token and pass the converted WordNet tag.
Exercise
Your corpus contains many product names and slang terms. After lemmatising, you suspect the lemmatiser changed little. How could you measure this using wn.synsets?
Show answer
Lemmatise each token with its tag, then check bool(wn.synsets(lemma, pos=pos)). Count the tokens where the result is False. A high share of unknown lemmas means the lexicon does not cover your vocabulary, so the lemmatiser is leaving many tokens untouched. You would then consider a stemmer, a domain lexicon, or subword tokenisation instead.
Exercise
A lemmatiser turns "happiness" into "happiness" and "organisation" into "organisation". Is this a bug?
Show answer
No. Lemmatisation reverses inflection (plural, tense, comparison), not derivation. "Happiness" is a derived noun, and it is its own lemma. A stemmer may merge it with "happy", but a lemmatiser keeps it separate.