AI Wiki中文/EN

Stemming and lemmatization: what should share a form?

词干提取与词形还原

Trace the original Porter suffix rules, distinguish retrieval stems from lemmas, and preserve ambiguity in a small explicit lexicon.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

A search key is not necessarily a dictionary word

Imagine a search box for documents about a cat. Matching cats to cat may be useful. Now compare mice with mouse: removing a final suffix alone will not make those forms agree. And if a procedure maps both university and universe to univers, it has merged two forms whose meanings a reader may want to keep separate.

These are original examples for two different operations. Stemming applies a rule system that produces a conflation key; the output need not be a word. Lemmatization seeks a lexical base form, often using a lexicon and grammatical information. Our Porter implementation produces studi from studies, while our separate finite lemma table returns study. The table is an explicit teaching dictionary, not an installed language model or a complete English lexicon.

Start after tokenization, with case and character handling already declared. Text normalization concerns string transformations such as Unicode normalization; linguistic structure explains why surface form, part of speech and context are different pieces of evidence.

Eight actual Porter stages change replacements only at1a and4. The finite lexicon keeps two verb lemmas for saw and leaves an unlisted input unresolved.
The1980 rule variant is explicit. Blue rows changed; m is the rule measure, and an empty candidate list means missing from this finite table.

Define the merge, then inspect the rules

A deterministic stem defines equivalence classes

For a fixed stemmer S on accepted words, define two inputs as equivalent when their stems match:

u∼Sv⟺S(u)=S(v).u\sim_S v\quad\Longleftrightarrow\quad S(u)=S(v).

This relation follows equality of keys, not equality of meanings. Merging unrelated forms is over-conflation; failing to merge forms that a task wants together is under-conflation. Both depend on the task’s desired distinctions. A count of fewer distinct keys does not itself show improved retrieval.

A lexicon can instead return a set of candidates, optionally conditioned on a part-of-speech tag p:

L(w,p)={ℓ:(w,p,ℓ)∈D}.L(w,p)=\{\ell:(w,p,\ell)\in\mathcal D\}.

In our small table, mice/NOUN returns mouse, and went/VERB returns go. For saw/VERB, it returns both saw and see: compare the invented contexts “they saw wood” and “they saw the comet.” Part of speech alone does not settle which lexical entry was intended. An empty candidate set means this table has no entry, not that the input has no possible lemma.

API return policy also matters. The pinned NLTK WordNet wrapper distinguishes methods that return all candidates, the first candidate, or the shortest candidate. Its lemmatize defaults to noun POS and returns the input unchanged if its candidate lookup is empty. None of these interface choices is evidence that a sentence’s intended sense has been resolved. We inspected the wrapper, not the entire WordNet database or its underlying morphology implementation. NLTK WordNet wrapper

Porter 1980: a precisely named variant

The following implementation follows the suffix rules reproduced as the 1980 algorithm in the fixed Snowball website source. It accepts lowercase ASCII letters, including the empty string. No automatic lowercasing, later exception list, BLI/LOGI extension or extra short-word guard is added. Naming this variant matters because a default library call may deliberately implement different behavior. Porter rule specification

The rule-defined vowels are a, e, i, o, u and a y preceded by a consonant. Initial y is a consonant; subsequent y takes the opposite status of the preceding letter. These are algorithmic letter classes, not a pronunciation model. Let c_i be1 for a consonant and0 for a vowel. Porter’s measure m counts transitions from a vowel run to a consonant run:

m(w)=∑i=1∣w∣−11[ci−1=0∧ci=1].m(w)=\sum_{i=1}^{|w|-1}\mathbf1[c_{i-1}=0\land c_i=1].

Equivalently, the pattern of runs is an optional consonant run, m vowel–consonant run pairs, and an optional vowel run:

w∈[C](VC)m[V].w\in[C](VC)^{m}[V].

Here C and V denote nonempty runs, not individual letters. The empty word has measure0. tree has0, trouble has1, troubles has2. Conditions also ask whether the candidate root contains a vowel, ends in a double consonant, or ends in consonant–vowel–consonant with the final letter excluding w, x and y.

Why a rule that matches may do nothing

Within a suffix group, select the longest matching suffix first, then check its condition on the root before that suffix. If the condition fails, that group leaves the word unchanged; it does not try a shorter suffix. Step1b illustrates why: feed matches eed, but its root f has measure0, so it stays feed. Falling back to ed would incorrectly expose fe as a root containing a vowel.

StageDecision in the 1980 rules
1aHandle plural endings with longest matching: sses, ies, ss, s
1bHandle eed under m>0; remove ed/ing only if the root contains a vowel, then apply the specified repair
1cChange final y to i only if the preceding root contains a vowel
2 and3Apply listed suffix replacements when root m>0
4Remove a listed suffix only when root m>1; ion additionally requires root-final s or t
5a and5bApply the final e and doubled-l conditions

The repair in1b can add e. Removing ed from seated leaves seat; because it ends in at, the intermediate result is seate. Step5a later removes that e. Checking only the final output would miss an implementation that took the wrong intermediate path.

For replacements, the changed stages are1a and4; all other recorded stages leave the current form alone:

replacements→1areplacement→4replac.\text{replacements}\xrightarrow{1a}\text{replacement} \xrightarrow{4}\text{replac}.

In step4, the longest matching suffix is ement, and replac has measure2. The code supplies the full suffix tables and explicit conditions below; it does not repeatedly strip arbitrary endings until the word looks short enough. Porter definitions and steps1a–5b

What the small table loses

Our executable list gives these results:

SurfacePorter stemSupplied lemma candidates
catscatcat/NOUN
micemicemouse/NOUN
wentwentgo/VERB
studiesstudistudy/NOUN, study/VERB
universityuniversnone in this table
universeuniversnone in this table

On a finite observed word set W, the number of merged distinctions can be counted as:

ΔS(W)=∣W∣−∣{S(w):w∈W}∣.\Delta_S(W)=|W|-|\{S(w):w\in W\}|.

This counts the reduction in distinct keys. It cannot tell whether a merger is useful: the university/universe pair contributes one regardless of whether the task wants those words together. Keep an unmodified-token baseline and evaluate the actual retrieval or analysis task on held-out examples.

For word length n and the fixed suffix tables, this implementation takes O(n) time and O(n) auxiliary/output space per word, assuming fixed-cost character operations. It performs a fixed number of suffix stages; constructing roots, computing letter classes and storing traces scan or copy O(n) characters. The lemma function scans all entries of its supplied dictionary; with D entries and word comparisons up to length n, the straightforward lookup is O(Dn) plus candidate sorting/output, not a constant-time full-language analyzer. An indexed lexicon could change that lookup cost.

See every stage, including the ones that leave the word alone

Save this complete standard-library program as stemming_lemmatization.py and run python3 stemming_lemmatization.py. It returns the rule variant, a comparison table, all eight stage records, ambiguous lemma candidates and an explicit unknown result. Invalid uppercase, punctuation or non-ASCII input is rejected so the demonstration does not silently invent a normalization policy.

"""Original implementation of the stated 1980 Porter suffix rules.

Accepts lowercase ASCII letters, including an empty string. No extra short-word
guard, BLI/LOGI extensions or exception list. This is not a default NLTK or Porter2
stemmer. The separate finite lemma table retains ambiguity and unknown words.
"""
import json
import re


def word_input(word):
    if not isinstance(word,str) or re.fullmatch(r'[a-z]*',word) is None:
        raise ValueError('A lowercase ASCII word without punctuation is required')
    return word


def consonants(word):
    word_input(word);flags=[]
    for letter in word:
        if letter in 'aeiou':flags.append(False)
        elif letter=='y':flags.append(not flags or not flags[-1])
        else:flags.append(True)
    return flags


def measure(word):
    flags=consonants(word)
    return sum(not flags[i-1] and flags[i] for i in range(1,len(flags)))


def vowel_present(word):return any(not v for v in consonants(word))


def double_consonant(word):
    return len(word)>=2 and word[-1]==word[-2] and consonants(word)[-1]


def cvc(word):
    return len(word)>=3 and consonants(word)[-3:]==[True,False,True] and word[-1] not in 'wxy'


def replace_longest(word,rules,condition):
    # One longest matching suffix is selected even if its condition then fails.
    for suffix,replacement in sorted(rules.items(),key=lambda pair:(-len(pair[0]),pair[0])):
        if word.endswith(suffix):
            root=word[:-len(suffix)]
            return root+replacement if condition(root,suffix) else word
    return word


def step1a(word):
    return replace_longest(word,{'sses':'ss','ies':'i','ss':'ss','s':''},lambda root,suffix:True)


def step1b(word):
    if word.endswith('eed'):
        return word[:-1] if measure(word[:-3])>0 else word
    for suffix in ['ing','ed']:
        if not word.endswith(suffix):continue
        root=word[:-len(suffix)]
        if not vowel_present(root):return word
        if root.endswith(('at','bl','iz')):return root+'e'
        if double_consonant(root) and root[-1] not in 'lsz':return root[:-1]
        if measure(root)==1 and cvc(root):return root+'e'
        return root
    return word


def step1c(word):return word[:-1]+'i' if word.endswith('y') and vowel_present(word[:-1]) else word


STEP2={'ational':'ate','tional':'tion','enci':'ence','anci':'ance','izer':'ize','abli':'able',
       'alli':'al','entli':'ent','eli':'e','ousli':'ous','ization':'ize','ation':'ate','ator':'ate',
       'alism':'al','iveness':'ive','fulness':'ful','ousness':'ous','aliti':'al','iviti':'ive','biliti':'ble'}
STEP3={'icate':'ic','ative':'','alize':'al','iciti':'ic','ical':'ic','ful':'','ness':''}
STEP4={suffix:'' for suffix in ['al','ance','ence','er','ic','able','ible','ant','ement','ment','ent',
                               'ion','ou','ism','ate','iti','ous','ive','ize']}


def step2(word):return replace_longest(word,STEP2,lambda root,suffix:measure(root)>0)
def step3(word):return replace_longest(word,STEP3,lambda root,suffix:measure(root)>0)
def step4(word):return replace_longest(word,STEP4,lambda root,suffix:measure(root)>1 and (suffix!='ion' or root.endswith(('s','t'))))


def step5a(word):
    if word.endswith('e'):
        root=word[:-1];m=measure(root)
        if m>1 or (m==1 and not cvc(root)):return root
    return word


def step5b(word):
    return word[:-1] if word.endswith('ll') and double_consonant(word) and measure(word)>1 else word


def stem_trace(word):
    raw=word_input(word);stages=[]
    for name,operation in [('1a',step1a),('1b',step1b),('1c',step1c),('2',step2),('3',step3),('4',step4),('5a',step5a),('5b',step5b)]:
        before=word;word=operation(word)
        stages.append({'step':name,'before':before,'after':word,'changed':before!=word,'measure_after':measure(word)})
    return {'raw':raw,'stem':word,'variant':'1980 rules on lowercase ASCII; no later extensions','stages':stages}


def stem(word):return stem_trace(word)['stem']


# An explicitly supplied, non-exhaustive lexicon, independent of the stemmer.
LEMMA_TABLE={('cats','NOUN'):['cat'],('mice','NOUN'):['mouse'],('went','VERB'):['go'],
             ('running','VERB'):['run'],('saw','NOUN'):['saw'],('saw','VERB'):['saw','see'],
             ('saws','NOUN'):['saw'],('sawing','VERB'):['saw'],('axes','NOUN'):['ax','axis'],
             ('studies','NOUN'):['study'],('studies','VERB'):['study'],('better','ADJ'):['good']}


def lemma_candidates(word,pos=None):
    word_input(word)
    if pos not in [None,'NOUN','VERB','ADJ']:raise ValueError('Choose NOUN, VERB, ADJ or unspecified POS')
    return [{'pos':tag,'lemma':lemma} for (surface,tag),lemmas in sorted(LEMMA_TABLE.items())
            if surface==word and (pos is None or tag==pos) for lemma in sorted(lemmas)]


def demo():
    words=['cats','mice','went','running','saw','sawing','studies','university','universe','news','lying','s','is']
    table=[{'word':word,'stem':stem(word),'lemmas':lemma_candidates(word)} for word in words]
    collisions={}
    for row in table:collisions.setdefault(row['stem'],[]).append(row['word'])
    return {'variant':'1980 Porter rules, not NLTK default or Porter2','table':table,
            'trace':stem_trace('replacements'),
            'ambiguous_even_with_pos':lemma_candidates('saw','VERB'),
            'unknown_lemma':lemma_candidates('unlistedword','NOUN'),
            'collisions':{key:value for key,value in collisions.items() if len(value)>1},
            'short_words':{word:stem(word) for word in ['','a','s','is','by','y']},
            'scope':'Retrieval stems need not be dictionary words. Lemmas come only from the declared finite table; POS does not always resolve ambiguity. No learned disambiguation, full English lexicon or retrieval-quality benchmark.'}


if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2))

The original tests check rules and intermediate values, including seated, longest-match failure, y classification and short words. An additional comparison used a fixed Snowball vocabulary/output pair:42,589 lowercase-ASCII inputs matched their reference final stems;14 of the42,603 supplied inputs were outside this program’s domain and were not counted as passing. This finite comparison does not prove equality on every possible string, and reference final outputs do not replace intermediate-stage tests.

A variant name and a POS tag are both part of the result

The unextended rules produce news → new, lying → ly, s → the empty string and is → i. A default NLTK Porter result should not be assumed identical: the inspected version enables NLTK_EXTENSIONS by default, has an exception pool, and protects words of length at most2 outside ORIGINAL_ALGORITHM mode. These are intended variant choices, not evidence that one output comparison identifies a bug. We did not run NLTK or compare its entire implementation. Pinned NLTK variant controls

The finite lemma table demonstrates irregular forms and ambiguity but cannot analyze an unlisted word. Real applications may need larger lexicons, language-specific morphological rules or context-sensitive models, with their own data and error analysis. English suffix rules do not transfer automatically to Chinese or to another language’s inflection system. Retain the surface token, POS assumptions and chosen output policy when displaying a lemma. Do not replace a user’s original wording with a retrieval key such as univers.

Follow a rule and challenge a merge

  1. What is the measure of tree, trouble and troubles? Does it count syllables?

Answer: The measures are0,1 and2. Count transitions from a rule-defined vowel run to a consonant run. This is a letter-pattern condition used by the suffix rules, not a syllable counter or a pronunciation claim.

  1. Why does feed stay unchanged in step1b, while seated passes through seate?

Answer: feed first selects the longer suffix eed; its root f fails m>0, and the group stops without trying ed. seated selects ed; seat contains a vowel and ends in at, so the repair adds e. Final step5a then yields seat.

  1. If saw is tagged VERB, is returning see always correct?

Answer: No. “They saw wood” can use the base verb saw, while “they saw the comet” uses the past of see. Our table retains both. Picking the first or shortest candidate is an API policy, not contextual evidence; a system must either disambiguate or preserve the uncertainty.

  1. A search experiment reports fewer unique keys after stemming. What must be checked before calling it an improvement?

Answer: Compare retrieval results with an unmodified-token baseline under the same queries and relevance judgments. Inspect both helpful matches and unwanted mergers such as university with universe, as well as missed irregular matches. Record the exact stemmer variant, preprocessing and data split; a smaller vocabulary alone is not a relevance metric.

Reproduce the rule system, not a vague algorithm label

The fixed Snowball website source reproduces the1980 rule specification used here. NLTK’s small WordNet wrapper clarifies candidate-return policies; its Porter controls show why named implementations can differ. These readings support rule and interface claims, not a whole-library audit or a retrieval-quality result. The original table and executable trace expose those distinctions without copying an upstream implementation.

Make a prediction, then check

For the surface word saw, does knowing VERB always leave one lemma in the supplied lexicon?

Choose one answer

Learning objectives

  • Distinguish retrieval-key conflation from a lexical lemma.
  • Compute Porter measure and follow conditional suffix stages.
  • Keep POS-conditioned lemma ambiguity and unknowns visible.
  • Evaluate over-conflation and distinguish algorithm variants.

Prerequisites & connections

Explore related knowledge →

References

  1. The Porter stemming algorithm: 1980 rules
    Martin Porter; Snowball contributors · 2026
  2. NLTK 3.9.2 WordNet lemmatizer wrapper
    NLTK contributors · 2025
  3. NLTK 3.9.2 Porter variant controls
    NLTK contributors · 2025

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-08 · Codex single-AI-author technical check: fixed1980 Porter rule block and pinned NLTK wrapper/variant scope; six paired equations, longest matching before condition, y/measure and all suffix stages, finite lexical candidates with unresolved POS ambiguity, four explained exercises and computed SVGs. Actual MDX matched42589 supported reference inputs,14 unsupported excluded. Not full-language morphology, upstream execution or human peer review.

  • Compared both languages: key equivalence versus lexical candidates, original1980 variant, rule-defined consonants and measure, longest-match failure without shorter fallback, complete1a–5b stages, intermediate seate and final seat, POS ambiguity and missing lexicon entry, complexity, six equations and four explained exercises.
  • Formal suite embeds15 independent rule/lexicon cases plus original trace/measure checks and6 publication checks. Official pinned vocabulary final-stem comparison reran actual MDX:42589 supported matches,14 domain exclusions. Data consumed computationally, not manually read row by row; reference data not redistributed.
  • Four original SVGs bind actual output and raw data. Final isolated bilingual, three-width/four-font validation passed and desktop/mobile screenshots were inspected. Full article acceptance is recorded separately. Single-AI-author technical check, not independent human review; no upstream code copied or executed.
  • Post-registration correction: schema kind changed from invalid algorithm to concept. Exact body, code, equations, references and original six-file freeze preserved; production test-module shadowing fixed. Explicit correction diffs retained; repeat formal/content/build checks before publication acceptance.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.