Algorithm Search⌘K

Algorithmcore

Porter stemmer

Also called Porter stemming algorithm.

Removes English suffixes in five rule phases, each rule guarded by a condition on the measure of the remaining stem.

Time
O(n) worst · best
Space
O(n) extra
Where
n = the number of letters of the word
Properties
not comparison baseddeterministiciterative

The Porter stemmer is a rule-based algorithm that maps an English word to a stem by removing its suffixes in five steps, so that words such as "connected", "connecting" and "connections" all map to "connect". Each rule has the form (condition) S1 → S2: if the word ends with S1 and the part before S1 meets the condition, S1 is replaced by S2. Most conditions test the measure mm of that part, a count of its vowel-consonant sequences, so that a suffix is removed only from a stem that is long enough. Martin Porter published it in 1980 as one algorithm for the technique of stemming, and it is still the standard English stemmer of information retrieval.

In plain words

Many English words share one root and differ only in their end: "hope", "hopeful", "hopefulness". A search for one form should usually find the others. The Porter stemmer cuts the end of a word in a fixed order of steps. The first step handles plurals and the endings "-ed" and "-ing". The middle steps turn long endings such as "-ational" or "-iveness" into shorter ones, or drop them. The last step removes a final "e" and one of two final "l" letters.

Each cut has a test. The part of the word that stays must be long enough, counted in groups of vowels followed by consonants. So one step turns "relational" into "relate", but "rational" keeps its "-ational", because "r" alone is too short. The result does not need to be a real word: "ponies" becomes "poni".

The problem

Input. A word ww of lower case letters a to z.

Output. A string, the stem of ww, such that words with the same root tend to get the same stem. Equal stems are what an inverted index uses: the index stores the stem in place of the word, and a query word is stemmed in the same way.

There is no exact specification of "the same root", so the algorithm is defined by its rules, and correctness means that the code does what the rules say. Porter gives these definitions.

  • Consonant and vowel. A consonant is a letter other than a, e, i, o, u, and other than a y that follows a consonant. Every other letter is a vowel. In "toy" the consonants are t and y, and in "syzygy" they are s, z and g.
  • Measure. Write C for a nonempty run of consonants and V for a nonempty run of vowels. Every string has the form [C](VC)m[V][C](VC)^m[V], where square brackets mean that the part may be missing. The number mm is the measure. For example m=0m = 0 for "tr", "ee", "tree", "y", "by"; m=1m = 1 for "trouble", "oats", "trees", "ivy"; m=2m = 2 for "troubles", "private", "oaten", "orrery".
  • Conditions on the stem vv, the part before S1: (m>k)(m > k) and (m=k)(m = k) test the measure of vv; *S means vv ends with s (and so for every letter); *v* means vv contains a vowel; *d means vv ends with a double consonant, such as tt or ss; *o means vv ends consonant, vowel, consonant, and the last consonant is not w, x or y, as in "hop" or "wil".
  • One rule per step. In each step, the rule with the longest S1 that ends the word is the only candidate. If its condition fails, the step does nothing; the step does not try a shorter S1.

The algorithm

  1. PORTER-STEM(w) ▷ w is a word of lower case letters
  2. 1for each step s in 1a, 1b, 1c, 2, 3, 4, 5a, 5b, in this order do
  3. 2R ← the rule (C) S1 → S2 of step s with the longest S1 that ends w
  4. 3if there is no such rule then go on to the next step
  5. 4v ← w without its last |S1| letters ▷ the stem before S1
  6. 5if C holds for v then
  7. 6w ← v · S2
  8. 7if s = 1b and S1 is "ed" or "ing" then w ← TIDY-1B(w)
  9. 8return w
  10. TIDY-1B(w) ▷ after "ed" or "ing" is removed
  11. 9if w ends with "at", "bl" or "iz" then return w · "e"
  12. 10if w ends with a double consonant other than l, s or z then return w without its last letter
  13. 11if MEASURE(w) = 1 and w ends consonant, vowel, consonant (not w, x, y) then return w · "e"
  14. 12return w
  15. MEASURE(v)
  16. 13m ← 0
  17. 14for i ← 1 to |v| - 1: if letter i of v is a vowel and letter i + 1 is a consonant then m ← m + 1
  18. 15return m

These are the rules of the paper, with Porter's own examples of what each step does to a word.

step rules examples
1a sses → ss, ies → i, ss → ss, s → (none) caresses → caress, ponies → poni, ties → ti, caress → caress, cats → cat
1b (m > 0) eed → ee, (*v*) ed → (none), (*v*) ing → (none) feed → feed, agreed → agree, plastered → plaster, bled → bled, motoring → motor, sing → sing
1b, tidy at → ate, bl → ble, iz → ize, (*d and not (*L or *S or *Z)) → one letter less, (m = 1 and *o) → add e conflated → conflate, troubled → trouble, sized → size, hopping → hop, tanned → tan, falling → fall, hissing → hiss, fizzed → fizz, failing → fail, filing → file
1c (*v*) y → i happy → happi, sky → sky
2 all (m > 0): 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 relational → relate, conditional → condition, rational → rational, digitizer → digitize, callousness → callous, sensibiliti → sensible
3 all (m > 0): icate → ic, ative → (none), alize → al, iciti → ic, ical → ic, ful → (none), ness → (none) triplicate → triplic, formative → form, electrical → electric, hopeful → hope, goodness → good
4 all (m > 1): al, ance, ence, er, ic, able, ible, ant, ement, ment, ent, ou, ism, ate, iti, ous, ive, ize → (none); (m > 1 and (*S or *T)) ion → (none) revival → reviv, airliner → airlin, replacement → replac, adjustment → adjust, adoption → adopt, effective → effect
5a (m > 1) e → (none), (m = 1 and not *o) e → (none) probate → probat, rate → rate, cease → ceas
5b (m > 1 and *d and *L) → one letter less controll → control, roll → roll

Walk-through. Line L2 finds the candidate rule of a step by the longest match: "caresses" ends with both "sses" and "s", and the rule sses → ss wins. Lines L4 and L5 test the condition on the stem vv, not on the whole word: in step 4, "replacement" has vv = "replac" with m=2m = 2, so "ement" goes. If the condition fails, the step leaves ww alone: "feed" ends with "eed", its stem "f" has m=0m = 0, and the rule (*v*) ed is not tried. Line L7 runs the second part of step 1b only after "ed" or "ing" was removed. That part puts back an "e" that the suffix took ("conflat" → "conflate"), undoes a doubled consonant ("hopp" → "hop"), or adds "e" to a short stem that ends like "fil" ("fil" → "file"). The two rules of step 5a share S1 = "e" and form one rule whose condition is the "or" of the two.

Example

The state after each step, for eight words.

word 1a 1b 1c 2 3 4 5a 5b
caresses caress
ponies poni
hopping hop
happy happi
relational relate relat
connections connection connect
generalizations generalization generalize general gener
oscillators oscillator oscillate oscill oscil

An empty cell is a step that did nothing. "Relational" shows that a word can lose parts of its suffix in several steps: Porter's example "relational → relate" is the effect of step 2 only, and the stem is "relat". The chains for "generalizations" and "oscillators" are the ones Porter gives in the paper.

On the toy collection. The 50 distinct terms of the toy collection of the information retrieval pages give 46 stems. Four pairs merge: "document" and "documents", "list" and "lists", "merge" and "merges", "sort" and "sorted". So the query word "documents" of q3q_3 now matches "document" in d4d_4, and the index entry for "list" also holds d5d_5, which has "lists" and is the most relevant document for q2q_2. Without stemming, neither of these words matches anything in those documents.

Correctness

Claim. For every word ww of lower case letters, PORTER-STEM returns the string that the rules of Porter (1980) give: steps 1a to 5b in order, in each step only the rule with the longest matching S1, applied if and only if its condition holds for the stem.

The key facts are two. First, MEASURE counts the positions where a vowel is followed by a consonant, and in the form [C](VC)m[V][C](VC)^m[V] these are exactly the mm boundaries between a V and the C after it. Second, the consonant status of a letter depends only on the letters before it, so the status of the letters of a stem vv is the same in vv as in ww, and the conditions can be evaluated on vv alone. With these, each step is a direct reading of the rule of the longest match. The full proof is in the proof file below.

Proof: PORTER-STEM applies the rules of Porter (1980) exactly, and its output is never longer than its inputfull

Let w=w1w2⋯wnw = w_1 w_2 \cdots w_n be a word of lower case letters. The rules of the paper are fixed: for each step ss in the order 1a, 1b, 1c, 2, 3, 4, 5a, 5b there is a list of rules (C) S1→S2(C)\ S_1 \to S_2, and step 1b has a second part that runs only if its rule for "ed" or "ing" was applied. The paper says that in each step only one rule is obeyed, the one with the longest S1S_1 that ends the word, and that it is obeyed only if its condition CC holds for the stem, the word without S1S_1. We show that PORTER-STEM computes exactly this.

The type of a letter. By the definition of the paper, letter ii of a string xx is a consonant if it is not a, e, i, o or u, and it is not a y that follows a consonant. Write cx(i)c_x(i) for "letter ii of xx is a consonant".

Lemma 1. CONSONANT-FLAGS returns cx(1),…,cx(∣x∣)c_x(1), \ldots, c_x(|x|), and if vv is a prefix of xx then cv(i)=cx(i)c_v(i) = c_x(i) for i≤∣v∣i \le |v|.

Proof. The definition gives cx(i)c_x(i) from letter ii and, for a y, from cx(i−1)c_x(i-1); a y at position 1 follows no letter and is a consonant. The code computes the flags from left to right by exactly these cases, so by induction on ii each flag is right. The flag cx(i)c_x(i) depends only on letters 1,…,i1, \ldots, i, which are the same in vv and in xx, so the second claim follows by the same induction. □\square

So a condition on the stem vv can be evaluated on vv alone: the stem has the same consonants and vowels as the first ∣v∣|v| letters of the word.

Lemma 2. For every string vv, MEASURE(v)(v) (lines L13 to L15) returns the number mm in the form v=[C](VC)m[V]v = [C](VC)^m[V].

Proof. Cut the flag sequence of vv into maximal runs of equal flags. The runs alternate between consonant runs (C) and vowel runs (V), so the sequence of runs is [C](VC)m[V][C](VC)^m[V] for exactly one mm: mm is the number of V runs that are followed by a C run. Line L14 counts the positions ii where letter ii is a vowel and letter i+1i+1 is a consonant. Such a position is the last letter of a V run whose next run is a C run, and each V run followed by a C run has exactly one last letter. So the count is mm. □\square

Lemma 3. The helpers decide the conditions of the paper on a stem vv: HAS-VOWEL decides *v*, ENDS-DOUBLE-CONSONANT decides *d, and ENDS-CVC decides *o.

Proof. *v* says that some letter of vv is a vowel, which is "not every flag is a consonant". *d says that vv ends with a double consonant: the last two letters are equal and both are consonants, which is what ENDS-DOUBLE-CONSONANT tests with the flags of Lemma 1. Porter's C code tests only the flag of the last letter. The two readings differ only for a final yy whose last y is a consonant: a y is a consonant only after a vowel, so the y before it is then a vowel, and by the definition the stem does not end with a double consonant. *o says that the last three letters are consonant, vowel, consonant and the last letter is not w, x or y, which is what ENDS-CVC tests, with Lemma 1 for the flags. The tests *S, *T and *L compare the last letter. □\square

Lemma 4. In each step, line L2 finds the rule of the paper's longest match, or line L3 finds that no rule matches.

Proof. In each table no two rules have the same S1S_1; the two rules of step 5a with S1S_1 = "e" are written as one rule whose condition is (m > 1) or (m = 1 and not *o), which holds exactly when one of the two rules of the paper applies. For each length there is at most one suffix of ww of that length, so among the rules whose S1S_1 ends ww the longest is unique. Line L2 scans all rules and keeps a matching rule when its S1S_1 is strictly longer than the one kept, so at the end it holds that unique rule, or none. □\square

Lemma 5. Lines L4 to L7 do what the paper says once the rule (C) S1→S2(C)\ S_1 \to S_2 is chosen.

Proof. Line L4 forms the stem vv, the word without S1S_1. By Lemmas 1 to 3, line L5 evaluates CC on vv as the paper defines it. If CC fails, the paper obeys no rule in this step, and the code returns ww unchanged; it does not try a rule with a shorter S1S_1. If CC holds, line L6 replaces S1S_1 by S2S_2.

Line L7 runs the second part of step 1b exactly when the paper does: when the second or third rule of step 1b, for "ed" or "ing", was applied. TIDY-1B is that second part. Its rules at → ate, bl → ble, iz → ize have no condition and the longest S1S_1, so they win when they match (line L9). The other two rules have an empty S1S_1 and act on the whole word. They cannot both hold: *d needs the last two letters to be consonants, and *o needs the second last to be a vowel. Line L10 is the rule (*d and not (*L or *S or *Z)) → single letter, and line L11 is the rule (m = 1 and *o) → E. If none holds, line L12 leaves the word. □\square

Lemma 6. The rule of step 5b in the code, S1S_1 = "l" with the condition "MEASURE(v)>1(v) > 1 and vv ends with l", has the same effect as the paper's rule (m > 1 and *d and *L) → single letter.

Proof. The paper's rule tests the whole word ww and removes its last letter. The word ww ends with l and has *d and *L exactly when it ends with "ll", which is when the code's stem vv, ww without its last l, ends with l (an l is always a consonant). For such a word, removing the last l does not change the measure: the last two letters are consonants, so the last position is not the end of a V run, and the vowel-consonant positions of Lemma 2 are the same in ww and in vv. So the two conditions agree, and both rules remove the last letter. □\square

Theorem. For every word ww of lower case letters, PORTER-STEM(w)(w) returns the result of applying the steps 1a, 1b, 1c, 2, 3, 4, 5a and 5b of the paper to ww in this order, with the rule of the longest match in each step. With the definitive option, the step 2 table is the one of the definitive version and words of one or two letters are returned unchanged. The call ends after O(n)O(n) work, and its output has at most nn letters.

Proof. Line L1 runs the eight steps once each, in the order of the paper, and each step passes its output to the next. By Lemmas 4, 5 and 6 each step returns exactly the word that the paper's step gives on its input. The definitive option only changes the step 2 table and adds the test of length at the start, which is what that version specifies.

Each step scans a fixed number of rules with suffixes of at most 7 letters, and the condition and TIDY-1B make a fixed number of scans of the stem, so each step costs O(n)O(n) and the call costs O(n)O(n). In every rule ∣S2∣≤∣S1∣|S_2| \le |S_1|, so a step does not make the word longer. TIDY-1B adds at most one letter, and it runs only after "ed" or "ing" was removed, so the word of step 1b is still shorter than its input. By induction over the steps, the output has at most nn letters. ■\blacksquare

Complexity

  • Time, O(n)O(n). There are eight steps. Each one tests at most 21 suffixes of at most 7 letters, which is O(1)O(1) work. The condition reads the stem once: MEASURE and the tests *v*, *d and *o are each one scan of at most nn letters. TIDY-1B does at most three such scans. So each step costs O(n)O(n), and the whole word O(n)O(n). Every word is read at least once, so the bound is also the best case.
  • Space, O(n)O(n). The stem and the table of consonant flags have at most nn entries. The rule tables have fixed size.
  • For a collection. An indexer stems each distinct term once and keeps the result in a hash table, so the cost is linear in the length of the vocabulary, not of the text.

Properties

  • Shorter or equal. Every S2 is shorter than its S1 or as long, and TIDY-1B adds back at most one letter after removing at least two, so the stem has at most nn letters.
  • Not idempotent. A stem can be stemmed again to a different stem: "agreed" gives "agre", and "agre" gives "agr". Stem the words of the text and the query once each, never a stored stem.
  • No dictionary. The rules look only at letters, so the stems need not be words ("poni", "happi") and the stemmer works on new words. The measure prevents many errors: "wander" keeps its "er" because "wand" has m=1m = 1, so it does not join "wand". But a letter rule cannot see meaning, so some words of one root stay apart ("probe" gives "probe" and "probate" gives "probat") and some unrelated words share a stem.
  • A remark in the paper that the rules do not meet. Porter writes that RELATE and RELATIVITY are conflated by his algorithm. By the printed rules, "relate" gives "relat" (step 5a) and "relativity" gives "rel" (steps 1c, 2 and 3), so they are not.
  • English only. The suffixes and the measure are for English. Other languages need their own rules.

Variants and improvements

  • The definitive version. Porter's ANSI C and BCPL code, which he calls the definitive version, departs from the paper in three points: it adds the step 2 rule (m > 0) logi → log, so "archaeology" and "archaeological" both give "archaeolog"; it replaces (m > 0) abli → able by (m > 0) bli → ble, so "possibly" and "possible" both give "possibl"; and it leaves words of one or two letters alone, so "as" and "is" keep their s. The code below supports both versions. In both, it reads *d as the paper defines it, with both letters consonants; Porter's C code tests only the last letter, which gives a different answer only for a stem that ends with yy.
  • Porter2. Porter's later English stemmer in the Snowball language replaces the measure by regions of the word, leaves words of length 2 alone, removes the suffix "ly" and a few others, and has a short list of exceptions. On the sample vocabulary of the Snowball site, Porter and Porter2 give different stems for slightly over 5 percent of the words.
  • Other suffix strippers. The Lovins stemmer removes the longest ending from a long list in one pass and then repairs the stem with transformation rules; the Paice/Husk stemmer applies rules from a table iteratively. See stemming for the comparison.

When to use it

Use it when the collection is English text, the queries are short, and the engine should match the inflected and derived forms of a query word without a dictionary. It is fast, has no data files, and its errors are well known. Manning, Raghavan and Schuetze report that stemming increases recall and harms precision, and that for English it helps some queries and hurts others, so the total gain is small; measure it on the target collection. For a lemma that is a real dictionary word, or for languages with rich inflection, use a lemmatizer or a stemmer written for that language. For index size alone, front coding and other dictionary compression do not change the answers at all.

Pitfalls

  • Falling through to a shorter suffix. At line L5 a failed condition must end the step. If the code goes on to the next rule with a shorter S1, "feed" fails (m > 0) eed, then matches (*v*) ed with the stem "fe" and becomes "fe". The right code keeps only the rule of line L2 and leaves "feed" alone.
  • Running the tidy part every time. Line L7 runs TIDY-1B only after "ed" or "ing" was removed. If it runs on every word, "hop" gets an "e" by line L11 and becomes "hope", and "bled", whose "ed" stays because "bl" has no vowel, becomes "blede".
  • Counting vowels instead of vowel-consonant pairs. Line L14 counts a vowel only when a consonant follows it. If it counts every vowel, "tree" has a measure of 1 in place of 0, step 5a removes the e, and "tree" and "trees" become "tre".
  • Two different versions. The paper rules and the definitive rules give different stems for words such as "possibly". An index built with one version and queried with the other misses matches. Fix one version for the index and the queries.
  • Input outside the precondition. The rules assume lower case letters only. Fold case, and split or drop digits, apostrophes and hyphens, before the word reaches the stemmer.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

irtoy.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the information retrieval pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""The toy collection of the information retrieval pages.

Eight short documents, four queries with graded judgments and one fixed
run. Tokens are the lower-case words split on spaces, with no stemming
and no stop words. The helper holds only the data and the statistics
tokenize, tf, df, cf, doc_len and avgdl. Scoring and metrics live on the
pages that define them.
"""

DOCS = {
    1: "binary search finds a key in a sorted array",
    2: "merge sort merges two sorted runs into one sorted array",
    3: "an inverted index maps each term to a posting list",
    4: "a posting list is a sorted list of document ids",
    5: "skip pointers speed up the merge of two posting lists",
    6: "a hash table finds a key in constant expected time",
    7: "search engines rank documents by a score for the query",
    8: "the sorted array of ids is compressed with gap encoding",
}

N = len(DOCS)

QUERIES = {
    "q1": "sorted array search",
    "q2": "posting list merge",
    "q3": "rank documents",
    "q4": "quantum circuit",
}

# Graded judgments: 2 is highly relevant, 1 is relevant, absent is 0.
QRELS = {
    "q1": {1: 2, 2: 1, 8: 1},
    "q2": {5: 2, 4: 1, 3: 1},
    "q3": {7: 2},
    "q4": {},
}

# A fixed run for the metric pages, as scores per query.
RUN = {
    "q1": {1: 2.0, 6: 2.0, 8: 1.5, 2: 1.0, 4: 1.0},
}


def tokenize(text):
    """Lower-case words split on spaces."""
    return text.lower().split()


_TOKENS = {d: tokenize(t) for d, t in DOCS.items()}


def tf(term, doc_id):
    """Number of times term occurs in document doc_id."""
    return _TOKENS[doc_id].count(term)


def df(term):
    """Number of documents that contain term."""
    return sum(1 for toks in _TOKENS.values() if term in toks)


def cf(term):
    """Number of occurrences of term in the whole collection."""
    return sum(toks.count(term) for toks in _TOKENS.values())


def doc_len(doc_id):
    """Number of tokens in document doc_id."""
    return len(_TOKENS[doc_id])


def avgdl():
    """Average document length in tokens."""
    return sum(len(toks) for toks in _TOKENS.values()) / N
porter_stemmer.py 193 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/porter-stemmer/. The authors are listed in prov/MAYHA4.jsonl.
"""The Porter stemmer, with the rules of the 1980 paper.

With definitive=True the stemmer follows the later reference version of
Porter (the ANSI C and BCPL code) instead: it adds the rule LOGI -> LOG to
step 2, replaces ABLI -> ABLE by BLI -> BLE, and leaves words of one or two
letters alone.
"""

from typing import Callable

VOWELS = "aeiou"

Condition = Callable[[str], bool]
Rule = tuple[str, str, Condition]


def consonant_flags(w: str) -> list[bool]:
    """Return a list whose entry i tells if letter i of w is a consonant.

    A consonant is a letter other than a, e, i, o, u, and other than a y
    that follows a consonant. Precondition: w is lower case. Cost O(|w|).
    """
    flags: list[bool] = []
    for i, c in enumerate(w):
        if c in VOWELS:
            flags.append(False)
        elif c == "y":
            flags.append(i == 0 or not flags[i - 1])
        else:
            flags.append(True)
    return flags


def measure(v: str) -> int:
    """Return m for v written as [C](VC){m}[V]: the number of vowels directly followed by a consonant.

    Precondition: v is lower case. Cost O(|v|).
    """
    f = consonant_flags(v)
    m = 0  # @line L13
    for i in range(len(v) - 1):  # @line L14
        if not f[i] and f[i + 1]:
            m += 1
    return m  # @line L15


def has_vowel(v: str) -> bool:
    """The condition *v*: v contains a vowel. Cost O(|v|)."""
    return not all(consonant_flags(v))


def ends_double_consonant(v: str) -> bool:
    """The condition *d: v ends with two equal letters that are both consonants. Cost O(|v|).

    Porter's C code tests only that the last letter is a consonant. The two
    readings differ only for a final yy, whose y before the last is a vowel.
    """
    if len(v) < 2 or v[-1] != v[-2]:
        return False
    f = consonant_flags(v)
    return f[-1] and f[-2]


def ends_cvc(v: str) -> bool:
    """The condition *o: v ends consonant, vowel, consonant, and the last letter is not w, x or y. Cost O(|v|)."""
    if len(v) < 3 or v[-1] in "wxy":
        return False
    f = consonant_flags(v)
    return f[-3] and not f[-2] and f[-1]


def _m_gt(k: int) -> Condition:
    return lambda v: measure(v) > k


def _always(v: str) -> bool:
    return True


STEP_1A: list[Rule] = [("sses", "ss", _always), ("ies", "i", _always), ("ss", "ss", _always), ("s", "", _always)]
STEP_1B: list[Rule] = [("eed", "ee", _m_gt(0)), ("ed", "", has_vowel), ("ing", "", has_vowel)]
STEP_1C: list[Rule] = [("y", "i", has_vowel)]
STEP_2_PAIRS = [
    ("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"),
]
STEP_2: list[Rule] = [(a, b, _m_gt(0)) for a, b in STEP_2_PAIRS]
STEP_2_DEFINITIVE: list[Rule] = [(a, b, _m_gt(0)) for a, b in STEP_2_PAIRS if a != "abli"] + [
    ("bli", "ble", _m_gt(0)),
    ("logi", "log", _m_gt(0)),
]
STEP_3: list[Rule] = [
    (a, b, _m_gt(0))
    for a, b in [("icate", "ic"), ("ative", ""), ("alize", "al"), ("iciti", "ic"), ("ical", "ic"), ("ful", ""), ("ness", "")]
]
STEP_4_SUFFIXES = [
    "al", "ance", "ence", "er", "ic", "able", "ible", "ant", "ement", "ment",
    "ent", "ou", "ism", "ate", "iti", "ous", "ive", "ize",
]
STEP_4: list[Rule] = [(a, "", _m_gt(1)) for a in STEP_4_SUFFIXES] + [
    ("ion", "", lambda v: measure(v) > 1 and v[-1:] in ("s", "t")),
]
STEP_5A: list[Rule] = [("e", "", lambda v: measure(v) > 1 or (measure(v) == 1 and not ends_cvc(v)))]
# (m > 1 and *d and *L) -> single letter. The stem v is the word without its last l,
# so the word ends with ll exactly when v ends with l. Removing one consonant of a
# final run of consonants does not change m.
STEP_5B: list[Rule] = [("l", "", lambda v: measure(v) > 1 and v.endswith("l"))]


def tidy_1b(w: str) -> str:
    """The second part of step 1b, done after the rule ED or ING has removed its suffix. Cost O(|w|)."""
    if w.endswith(("at", "bl", "iz")):  # @line L9
        return w + "e"
    if ends_double_consonant(w) and w[-1] not in "lsz":  # @line L10
        return w[:-1]
    if measure(w) == 1 and ends_cvc(w):  # @line L11
        return w + "e"
    return w  # @line L12


def apply_step(rules: list[Rule], w: str, step: str = "") -> str:
    """Apply one step: the rule with the longest S1 that ends w, if its condition holds for the stem.

    Precondition: no two rules of the list have the same S1. Cost O(|w|) for a fixed rule list.
    """
    best = None
    for rule in rules:  # @line L2
        if w.endswith(rule[0]) and (best is None or len(rule[0]) > len(best[0])):
            best = rule
    if best is None:  # @line L3
        return w
    s1, s2, cond = best
    v = w[: len(w) - len(s1)]  # @line L4
    if not cond(v):  # @line L5
        return w
    w = v + s2  # @line L6
    if step == "1b" and s1 in ("ed", "ing"):  # @line L7
        w = tidy_1b(w)
    return w


def step_1a(w: str) -> str:
    return apply_step(STEP_1A, w)


def step_1b(w: str) -> str:
    return apply_step(STEP_1B, w, "1b")


def step_1c(w: str) -> str:
    return apply_step(STEP_1C, w)


def step_2(w: str, definitive: bool = False) -> str:
    return apply_step(STEP_2_DEFINITIVE if definitive else STEP_2, w)


def step_3(w: str) -> str:
    return apply_step(STEP_3, w)


def step_4(w: str) -> str:
    return apply_step(STEP_4, w)


def step_5a(w: str) -> str:
    return apply_step(STEP_5A, w)


def step_5b(w: str) -> str:
    return apply_step(STEP_5B, w)


def porter_stem(w: str, definitive: bool = False) -> str:
    """Return the Porter stem of w.

    Precondition: w is a word of lower case letters a to z (it may be empty).
    Cost O(|w|): eight steps, each with a fixed number of rules of bounded length.
    """
    if definitive and len(w) <= 2:
        return w
    steps = [
        (STEP_1A, "1a"), (STEP_1B, "1b"), (STEP_1C, "1c"),
        (STEP_2_DEFINITIVE if definitive else STEP_2, "2"),
        (STEP_3, "3"), (STEP_4, "4"), (STEP_5A, "5a"), (STEP_5B, "5b"),
    ]
    for rules, name in steps:  # @line L1
        w = apply_step(rules, w, name)
    return w  # @line L8
test_porter_stemmer.py 296 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/porter-stemmer/. The authors are listed in prov/MAYHA4.jsonl.

import random
import re

import irtoy
from porter_stemmer import (
    consonant_flags,
    ends_cvc,
    ends_double_consonant,
    has_vowel,
    measure,
    porter_stem,
    step_1a,
    step_1b,
    step_1c,
    step_2,
    step_3,
    step_4,
    step_5a,
    step_5b,
)

# ---------------------------------------------------------------------------
# The examples printed in Porter (1980), as in the copy of the paper on
# tartarus.org/martin/PorterStemmer/def.txt. Each step example is the effect
# of that step alone on the word given.
# ---------------------------------------------------------------------------

STEP_EXAMPLES = {
    step_1a: [("caresses", "caress"), ("ponies", "poni"), ("ties", "ti"), ("caress", "caress"), ("cats", "cat")],
    step_1b: [
        ("feed", "feed"), ("agreed", "agree"), ("plastered", "plaster"), ("bled", "bled"),
        ("motoring", "motor"), ("sing", "sing"),
        ("conflated", "conflate"), ("troubled", "trouble"), ("sized", "size"), ("hopping", "hop"),
        ("tanned", "tan"), ("falling", "fall"), ("hissing", "hiss"), ("fizzed", "fizz"),
        ("failing", "fail"), ("filing", "file"),
    ],
    step_1c: [("happy", "happi"), ("sky", "sky")],
    step_2: [
        ("relational", "relate"), ("conditional", "condition"), ("rational", "rational"),
        ("valenci", "valence"), ("hesitanci", "hesitance"), ("digitizer", "digitize"),
        ("conformabli", "conformable"), ("radicalli", "radical"), ("differentli", "different"),
        ("vileli", "vile"), ("analogousli", "analogous"), ("vietnamization", "vietnamize"),
        ("predication", "predicate"), ("operator", "operate"), ("feudalism", "feudal"),
        ("decisiveness", "decisive"), ("hopefulness", "hopeful"), ("callousness", "callous"),
        ("formaliti", "formal"), ("sensitiviti", "sensitive"), ("sensibiliti", "sensible"),
    ],
    step_3: [
        ("triplicate", "triplic"), ("formative", "form"), ("formalize", "formal"),
        ("electriciti", "electric"), ("electrical", "electric"), ("hopeful", "hope"), ("goodness", "good"),
    ],
    step_4: [
        ("revival", "reviv"), ("allowance", "allow"), ("inference", "infer"), ("airliner", "airlin"),
        ("gyroscopic", "gyroscop"), ("adjustable", "adjust"), ("defensible", "defens"),
        ("irritant", "irrit"), ("replacement", "replac"), ("adjustment", "adjust"),
        ("dependent", "depend"), ("adoption", "adopt"), ("homologou", "homolog"),
        ("communism", "commun"), ("activate", "activ"), ("angulariti", "angular"),
        ("homologous", "homolog"), ("effective", "effect"), ("bowdlerize", "bowdler"),
    ],
    step_5a: [("probate", "probat"), ("rate", "rate"), ("cease", "ceas")],
    step_5b: [("controll", "control"), ("roll", "roll")],
}


def test_measure_examples_of_the_paper():
    for w in ["tr", "ee", "tree", "y", "by"]:
        assert measure(w) == 0, w
    for w in ["trouble", "oats", "trees", "ivy"]:
        assert measure(w) == 1, w
    for w in ["troubles", "private", "oaten", "orrery"]:
        assert measure(w) == 2, w
    assert measure("") == 0
    assert measure("replac") == 2


def test_consonants_of_toy_and_syzygy():
    assert [c for c, f in zip("toy", consonant_flags("toy")) if f] == ["t", "y"]
    assert [c for c, f in zip("syzygy", consonant_flags("syzygy")) if f] == ["s", "z", "g"]


def test_conditions():
    assert ends_cvc("wil") and ends_cvc("hop")
    assert not ends_cvc("sow") and not ends_cvc("box") and not ends_cvc("say")
    assert ends_double_consonant("hiss") and not ends_double_consonant("bee")
    # In "syy" the last y is a consonant and the y before it is a vowel.
    assert consonant_flags("syy") == [True, False, True]
    assert not ends_double_consonant("syy") and not ends_double_consonant("yy")
    assert has_vowel("plaster") and not has_vowel("bl")


def test_longest_match_in_step_1a():
    assert step_1a("caresses") == "caress"
    assert step_1a("caress") == "caress"
    assert step_1a("cares") == "care"


def test_step_examples_of_the_paper():
    for step, pairs in STEP_EXAMPLES.items():
        for w, want in pairs:
            assert step(w) == want, (step.__name__, w)


def test_whole_words_of_the_paper():
    chain = ["generalizations", "generalization", "generalize", "general", "gener"]
    assert step_1a(chain[0]) == chain[1]
    assert step_2(chain[1]) == chain[2]
    assert step_3(chain[2]) == chain[3]
    assert step_4(chain[3]) == chain[4]
    assert porter_stem("generalizations") == "gener"
    assert step_1a("oscillators") == "oscillator"
    assert step_2("oscillator") == "oscillate"
    assert step_4("oscillate") == "oscill"
    assert step_5b("oscill") == "oscil"
    assert porter_stem("oscillators") == "oscil"
    for w in ["connect", "connected", "connecting", "connection", "connections"]:
        assert porter_stem(w) == "connect"


def test_lists_a_and_b_of_the_paper():
    for w in ["relate", "probate", "conflate", "pirate", "prelate"]:
        assert step_4(w) == w
    for w in ["derivate", "activate", "demonstrate", "necessitate", "renovate"]:
        assert step_4(w) == w[:-3]
    assert porter_stem("archprelate") == "archprel"
    assert porter_stem("probe") != porter_stem("probate")


def test_relate_and_relativity_by_the_printed_rules():
    # The paper says that the two words conflate, but the printed rules give two stems.
    assert porter_stem("relate") == "relat"
    assert porter_stem("relativity") == "rel"


def test_the_definitive_version():
    assert porter_stem("archaeology") != porter_stem("archaeological")
    assert porter_stem("archaeology", True) == porter_stem("archaeological", True) == "archaeolog"
    assert porter_stem("possibly") != porter_stem("possible")
    assert porter_stem("possibly", True) == porter_stem("possible", True) == "possibl"
    assert porter_stem("as") == "a" and porter_stem("is") == "i" and porter_stem("s") == ""
    assert porter_stem("as", True) == "as" and porter_stem("s", True) == "s"


def test_edge_cases():
    assert porter_stem("") == ""
    assert porter_stem("a") == "a"
    assert porter_stem("eeee") == "eeee"
    assert porter_stem("sss") == "sss"
    assert porter_stem("yyyy") == "yyyi"


def test_toy_collection():
    vocab = sorted({t for d in irtoy.DOCS for t in irtoy.tokenize(irtoy.DOCS[d])})
    assert len(vocab) == 50
    stems = {porter_stem(t) for t in vocab}
    assert len(stems) == 46
    # "lists" (d5) and "document" (d4) match the other form only after stemming.
    assert porter_stem("lists") == porter_stem("list") == "list"
    assert porter_stem("document") == porter_stem("documents") == "document"
    assert porter_stem("sorted") == porter_stem("sort")
    assert porter_stem("merges") == porter_stem("merge")


# ---------------------------------------------------------------------------
# An independent oracle: the rule tables written as in the paper, with the
# conditions read by a small evaluator, and m found from the collapsed C and V
# pattern of the stem.
# ---------------------------------------------------------------------------

TABLES = {
    "1a": "SSES -> SS; IES -> I; SS -> SS; S ->",
    "1b": "(m>0) EED -> EE; (*v*) ED ->; (*v*) ING ->",
    "1b2": "AT -> ATE; BL -> BLE; IZ -> IZE; (*d and not (*L or *S or *Z)) -> single; (m=1 and *o) -> E",
    "1c": "(*v*) Y -> I",
    "2": "(m>0) ATIONAL -> ATE; (m>0) TIONAL -> TION; (m>0) ENCI -> ENCE; (m>0) ANCI -> ANCE;"
    " (m>0) IZER -> IZE; (m>0) ABLI -> ABLE; (m>0) ALLI -> AL; (m>0) ENTLI -> ENT; (m>0) ELI -> E;"
    " (m>0) OUSLI -> OUS; (m>0) IZATION -> IZE; (m>0) ATION -> ATE; (m>0) ATOR -> ATE;"
    " (m>0) ALISM -> AL; (m>0) IVENESS -> IVE; (m>0) FULNESS -> FUL; (m>0) OUSNESS -> OUS;"
    " (m>0) ALITI -> AL; (m>0) IVITI -> IVE; (m>0) BILITI -> BLE",
    "3": "(m>0) ICATE -> IC; (m>0) ATIVE ->; (m>0) ALIZE -> AL; (m>0) ICITI -> IC; (m>0) ICAL -> IC;"
    " (m>0) FUL ->; (m>0) NESS ->",
    "4": "(m>1) AL ->; (m>1) ANCE ->; (m>1) ENCE ->; (m>1) ER ->; (m>1) IC ->; (m>1) ABLE ->;"
    " (m>1) IBLE ->; (m>1) ANT ->; (m>1) EMENT ->; (m>1) MENT ->; (m>1) ENT ->;"
    " (m>1 and (*S or *T)) ION ->; (m>1) OU ->; (m>1) ISM ->; (m>1) ATE ->; (m>1) ITI ->;"
    " (m>1) OUS ->; (m>1) IVE ->; (m>1) IZE ->",
    "5a": "(m>1) E ->; (m=1 and not *o) E ->",
    "5b": "(m>1 and *d and *L) -> single",
}


def parse(table):
    rules = []
    for part in table.split(";"):
        part = part.strip()
        cond = "True"
        if part.startswith("("):
            depth = 0
            for i, ch in enumerate(part):
                depth += ch == "("
                depth -= ch == ")"
                if depth == 0:
                    cond, part = part[1:i], part[i + 1 :].strip()
                    break
        left, right = [x.strip() for x in part.split("->")]
        rules.append((left.lower(), right.lower(), cond))
    return rules


def oracle_is_consonant(w, i):
    if w[i] in "aeiou":
        return False
    if w[i] == "y":
        return i == 0 or not oracle_is_consonant(w, i - 1)
    return True


def oracle_m(stem):
    cv = "".join("c" if oracle_is_consonant(stem, i) else "v" for i in range(len(stem)))
    form = re.sub("v+", "V", re.sub("c+", "C", cv))
    m = form.count("VC")
    assert re.fullmatch("C?(VC){%d}V?" % m, form)
    return m


def holds(cond, stem):
    if cond == "True":
        return True
    cv = [oracle_is_consonant(stem, i) for i in range(len(stem))]
    expr = cond.replace("=", "==").replace(">==", ">=")
    expr = re.sub(r"\bm\b", str(oracle_m(stem)), expr)
    expr = expr.replace("*v*", str(not all(cv)))
    expr = expr.replace("*d", str(len(stem) >= 2 and stem[-1] == stem[-2] and cv[-1] and cv[-2]))
    o = len(stem) >= 3 and cv[-3] and not cv[-2] and cv[-1] and stem[-1] not in "wxy"
    expr = expr.replace("*o", str(o))
    expr = re.sub(r"\*([A-Z])", lambda g: str(stem.endswith(g.group(1).lower())), expr)
    return eval(expr, {"__builtins__": {}})


def oracle_step(table, w):
    rules = parse(table)
    matching = [r for r in rules if r[0] and w.endswith(r[0])]
    if not matching:
        return w, None
    longest = max(len(r[0]) for r in matching)
    for s1, s2, cond in matching:
        if len(s1) == longest:
            stem = w[: len(w) - len(s1)]
            if holds(cond, stem):
                return stem + s2, s1
    return w, None


def oracle_conditional_rules(table, w):
    # Rules with an empty S1: the first one whose condition holds on the whole word.
    for s1, s2, cond in parse(table):
        if s1 == "" and holds(cond, w):
            return w[:-1] if s2 == "single" else w + s2
        if s1 and w.endswith(s1) and holds(cond, w[: len(w) - len(s1)]):
            return w[: len(w) - len(s1)] + s2
    return w


def oracle_stem(w, definitive=False):
    if definitive and len(w) <= 2:
        return w
    w, _ = oracle_step(TABLES["1a"], w)
    w, fired = oracle_step(TABLES["1b"], w)
    if fired in ("ed", "ing"):
        w = oracle_conditional_rules(TABLES["1b2"], w)
    w, _ = oracle_step(TABLES["1c"], w)
    t2 = TABLES["2"]
    if definitive:
        t2 = t2.replace("(m>0) ABLI -> ABLE", "(m>0) BLI -> BLE") + "; (m>0) LOGI -> LOG"
    for name in [t2, TABLES["3"], TABLES["4"], TABLES["5a"]]:
        w, _ = oracle_step(name, w)
    return oracle_conditional_rules(TABLES["5b"], w)


def test_oracle_on_the_paper_examples():
    assert oracle_stem("generalizations") == "gener"
    assert oracle_stem("oscillators") == "oscil"
    assert oracle_stem("hopping") == "hop"


def test_random_words_against_the_oracle():
    rng = random.Random(1980)
    suffixes = sorted({r[0] for t in TABLES.values() for r in parse(t) if r[0]} | {"bli", "logi", "ed", "ing", "y", "ll"})
    letters = "abcdefghijklmnopqrstuvwxyz" + "aeiouy" * 3 + "lstn" * 2
    for _ in range(3000):
        stem = "".join(rng.choice(letters) for _ in range(rng.randint(0, 6)))
        w = stem + "".join(rng.choice(suffixes) for _ in range(rng.randint(0, 3)))
        for definitive in (False, True):
            got = porter_stem(w, definitive)
            assert got == oracle_stem(w, definitive), (w, definitive)
            assert len(got) <= max(len(w), 2)

History

Julie Beth Lovins published an earlier stemmer in 1968. Porter wrote his algorithm in 1979 at the Computer Laboratory in Cambridge, as part of a larger IR project, and it appeared as Chapter 6 of the final project report by van Rijsbergen, Robertson and Porter before its publication in Program in 1980. In the paper he reports a test on the Cranfield 200 collection, where the new, simpler stemmer gave better retrieval than a much more elaborate program in use in IR research in Cambridge since 1971, and the effect of the rules on a vocabulary of 10,000 words: 3597 words were reduced in step 1, 766 in step 2, 327 in step 3, 2424 in step 4 and 1373 in step 5 (a word can be reduced in more than one step), 3650 were not reduced, and the result had 6370 distinct stems, about one third fewer than words. Porter later published the definitive C and BCPL versions and, in Snowball, the Porter2 stemmer.

References

  1. Martin F. Porter, An algorithm for suffix stripping, Program 14(3), 130 to 137, 1980, Section 2, The algorithm (the definitions of consonant, vowel and the measure m, the conditions *S, *v*, *d and *o, the rule of the longest matching suffix, Steps 1a to 5b with their examples, and the counts of words reduced in each step for a vocabulary of 10,000 words)
  2. Martin Porter, The Porter Stemming Algorithm, web page at tartarus.org/martin/PorterStemmer, the note on the points where the ANSI C and BCPL versions depart from the published algorithm (the rule LOGI to LOG, the rule BLI to BLE in place of ABLI to ABLE, and words of length 1 or 2 left alone)
  3. Martin Porter, The English (Porter2) stemming algorithm, web page at snowballstem.org/algorithms/english/stemmer.html, the list of points where Porter2 departs from the 1980 algorithm, and the statement that the two stem slightly over 5 percent of the words of the sample vocabulary differently
  4. Christopher D. Manning, Prabhakar Raghavan and Hinrich Schuetze, Introduction to Information Retrieval, Cambridge University Press, 2008, Chapter 2, Section 2.2.4 (stemming and lemmatization, the five phases of the Porter stemmer, the rule SSES to SS, the measure condition, and the comparison with the Lovins and Paice stemmers)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example