Sub topic 8
The Porter and Snowball stemmers in practice
Prerequisites
This chapter assumes you know:
- Basic Python, including regular expressions.
- What a stem is and how it differs from a lemma, from the earlier morphology chapter.
- The idea of suffix stripping, from the previous chapter on stemming.
You also need NLTK installed (pip install nltk). The stemmers used here need no extra data downloads.
Two stemmers, one family
The Porter stemmer (Martin Porter, 1980) is the classic English suffix stripper. It applies a fixed sequence of rewrite rules, and each rule fires only if the remaining stem satisfies a condition.
The Snowball stemmer, also called Porter2 for English, is Porter's later redesign. Snowball is also a small language for writing stemmers. It has been used to build stemmers for many languages, including French, German, Spanish and Russian.
Both return a stem, not a dictionary word. Run this to see it:
from nltk.stem import PorterStemmer, SnowballStemmer
porter = PorterStemmer()
snowball = SnowballStemmer("english")
for word in ["caresses", "ponies", "running", "studies"]:
print(word, porter.stem(word), snowball.stem(word))This prints caress, poni, run and studi in both columns. The stems poni and studi are not English words. That is normal. A stem only has to be the same for related words, so "pony" and "ponies" both reach poni.
How Porter works internally
Porter's algorithm has five groups of rules, run in order. Each step can change the word, and later steps see the result of earlier ones.
The measure
Many rules carry a condition on the measure m of the stem that would remain. Porter describes every word as [C](VC)^m[V]. C is a run of consonants, V is a run of vowels, and m counts the vowel-consonant pairs. The letter y counts as a vowel when it follows a consonant.
| Word | Pattern | m |
|---|---|---|
| tree | CV | 0 |
| trouble | CVCV | 1 |
| oats | VC | 1 |
| troubles | CVCVC | 2 |
| private | CVCVCV | 2 |
The measure is a rough count of syllables. It stops the algorithm from cutting short words down to nothing. A rule such as (m>0) eed -> ee turns "agreed" into "agree" but leaves "feed" alone. Removing "-ed" from "feed" would leave "fe", which has m = 0.
Reproducing the first steps
This script computes the measure and implements Step 1a. It needs no libraries.
import re
def form(word):
pattern = ""
for i, ch in enumerate(word):
if ch in "aeiou":
pattern += "V"
elif ch == "y" and i > 0 and pattern[-1] == "C":
pattern += "V"
else:
pattern += "C"
return pattern
def measure(word):
collapsed = re.sub(r"(.)\1*", r"\1", form(word))
return collapsed.count("VC")
def step1a(word):
if word.endswith("sses") or word.endswith("ies"):
return word[:-2]
if word.endswith("ss"):
return word
if word.endswith("s"):
return word[:-1]
return word
for w in ["tree", "trouble", "oats", "troubles", "private"]:
print(w, form(w), measure(w))
for w in ["caresses", "ponies", "caress", "cats"]:
print(w, step1a(w))The last loop prints caress, poni, caress and cat. The rule order inside Step 1a matters. "caress" must match the ss rule before the plain s rule, or it would lose its final letter.
Step 1b and its repair rules
Step 1b removes "-ed" and "-ing" only if the stem contains a vowel. Then it repairs what is left:
- If the stem now ends in
at,bloriz, aneis added: "conflated" becomes "conflate". - If it ends in a double consonant other than
l,sorz, one is dropped: "hopping" becomes "hop". - If it is short and ends consonant-vowel-consonant, an
eis added: "hoping" becomes "hope".
The last two rules keep "hopping" and "hoping" apart. Those words come from different verbs, "hop" and "hope".
What Snowball changes
Snowball English keeps Porter's overall design, but it changes several parts.
| Aspect | Porter | Snowball (Porter2) |
|---|---|---|
| Rule condition | Measure `m` of the stem | Regions R1 and R2 of the word, defined by vowel-consonant boundaries |
| Special words | None | Exception lists, for example for "skis", "dying" and "news" |
| "-ly" and "-li" endings | Mostly left in place | Handled by extra rules |
| Languages | English | Many languages, with English as one of them |
| Stopword option in NLTK | None | `ignore_stopwords=True` |
The differences show up in real words:
from nltk.stem import PorterStemmer, SnowballStemmer
porter = PorterStemmer()
snowball = SnowballStemmer("english")
for word in ["generously", "fairly", "university", "universe"]:
print(word, porter.stem(word), snowball.stem(word))Porter reduces "generously" to gener, and Snowball gives generous. Porter turns "fairly" into fairli, and Snowball gives fair. Snowball's extra rules match what people expect more often here. Both stemmers still send "university" and "universe" to univers. This is an overstemming error, covered in the next chapter, and Snowball does not fix it.
Using the stemmers in NLTK
Choosing a mode
NLTK's PorterStemmer adds a few extensions to Porter's paper by default. If you need to match a published result, select the original algorithm:
from nltk.stem import PorterStemmer
original = PorterStemmer(mode=PorterStemmer.ORIGINAL_ALGORITHM)
default = PorterStemmer()
print(original.stem("ponies"), default.stem("ponies"))The constants ORIGINAL_ALGORITHM, MARTIN_EXTENSIONS and NLTK_EXTENSIONS select the variant. For new projects, most people use Snowball and ignore the mode.
Other languages and stopwords
SnowballStemmer.languages lists the supported languages. Pick one by name:
from nltk.stem import SnowballStemmer
print(SnowballStemmer.languages)
french = SnowballStemmer("french")
print(french.stem("continuellement"))
plain = SnowballStemmer("english")
careful = SnowballStemmer("english", ignore_stopwords=True)
print(plain.stem("having"), careful.stem("having"))With ignore_stopwords=True, a word on NLTK's stopword list for that language is returned unchanged. The plain stemmer gives have and the careful one keeps having. This is useful if you later match stopwords against the original forms.
Stemming in a search pipeline
The standard use of a stemmer is to make a query match documents that use other forms of the same word. Both sides must go through the same analysis.
import re
from collections import defaultdict
from functools import lru_cache
from nltk.stem import SnowballStemmer
stemmer = SnowballStemmer("english")
@lru_cache(maxsize=None)
def stem(token):
return stemmer.stem(token)
def analyse(text):
return [stem(t) for t in re.findall(r"\w+", text.lower())]
docs = {
1: "The runners were running quickly",
2: "She runs every morning",
3: "A run of bad luck",
}
index = defaultdict(set)
for doc_id, text in docs.items():
for term in analyse(text):
index[term].add(doc_id)
print(sorted(index[stem("runs")]))
print(sorted(index[stem("running")]))Both queries print [1, 2, 3], because "runs", "running" and "run" all reduce to run. The lru_cache is worth having. Natural text repeats a small set of words many times, and stemming is slower than a dictionary lookup.
Lower-casing in analyse keeps the stemmer's input uniform. NLTK's stemmers also lower-case their input, but you should not depend on that, because your own matching code may see the original case.
Common errors
- Stemming only one side. If you stem the documents but not the query, "running" will never match
run. Use oneanalysefunction for both. - Stemming before tokenising. The stemmer takes one token at a time. Pass it the output of the tokeniser, not a raw sentence.
- Showing stems to users.
studiis fine inside an index but wrong in a results page. Keep the original text for display. - Mixing stemmers across index versions. If you rebuild the index with a different stemmer, old stored stems no longer match new queries. Record the stemmer name and version with the index.
- Expecting dictionary words. Do not look stems up in a word list. Use a lemmatiser when you need valid base forms.
- Stemming where word form carries meaning. Sentiment, named entities and part-of-speech tagging often depend on the exact word form. Stemming "better" or "Apple" can remove information that the task needs.
Exercises
Exercise
Compute the Porter measure m of "oaten" and of "orrery", writing out each word as a C/V pattern first.
Show answer
"oaten" is V V C V C, which collapses to VCVC. That contains VC twice, so m = 2. "orrery" is V C C V C V, which collapses to VCVCV (the final y follows a consonant, so it counts as a vowel). That contains VC twice, so m = 2.
Exercise
A search index was built with SnowballStemmer("english"). A user searches for "fairly". Explain what happens if the query code uses PorterStemmer() instead, and how to prevent it.
Show answer
Snowball stores "fairly" as fair, but Porter turns the query into fairli. The query term is not in the index, so documents containing "fairly" are not found. Prevent this by using one shared analysis function, and the same stemmer, for both indexing and querying. Record the stemmer name with the index.
Exercise
Why does Porter's Step 1b turn "hopping" into "hop" but "hoping" into "hope"?
Show answer
After removing "-ing", Step 1b repairs the stem. "hopp" ends in a double consonant (not l, s or z), so one p is dropped, giving "hop". "hop" is a short consonant-vowel-consonant stem, but the "e" rule applies to the other word: "hop" from "hoping" ends consonant-vowel-consonant with a single consonant and was never doubled, so an "e" is added to give "hope". The doubled consonant in the original spelling is the evidence that separates the two words.