Clean text with stopword removal and a rule-based suffix stemmer

Why it matters Stopword removal and stemming are still used in BM25 search indexes, keyword features and quick text baselines.

Classic text pipelines shrink vocabulary by removing stopwords and stemming words to a rough root. A minimum stem length stops rules from destroying short words like 'sing' or 'red'.

Write preprocess(text, stopwords). Lowercase the text and take tokens with the regex [a-z0-9]+. Drop tokens in the stopwords set. For each remaining token, try the suffixes 'ing', 'ed', 'ly', 'es', 's' in that order and remove the FIRST one that the token ends with AND that leaves a stem of at least 3 characters; remove at most one suffix, and if no suffix qualifies keep the token unchanged. Return the list of resulting tokens.

Signaturedef preprocess(text, stopwords)

Example

preprocess('The cats are running quickly!', {'the', 'are'}) is ['cat', 'runn', 'quick'].

Understand the idea

Stopwords are very common words like 'the' and 'are' that carry little meaning for search or classification. Stemming cuts words to a rough root so 'cats' and 'cat', or 'running' and 'run...', share one feature. A stemmer is a list of suffix rules; the first rule that fits wins. A minimum stem length prevents damage to short words.

Worked example: 'The cats are running quickly!' lowercased and tokenized gives the, cats, are, running, quickly. Drop the and are. 'cats' does not end in 'ing', 'ed', 'ly' or 'es', but ends in 's', and 'cat' has 3 letters, so it becomes 'cat'. 'running' ends in 'ing' and leaves 'runn'. 'quickly' ends in 'ly' and leaves 'quick'. 'sing' would leave 's', too short, so it stays 'sing'.

Rule: strip the first suffix s in order with word.endswith(s) and len(word) - len(s) >= 3.

BM25 search engines and bag-of-words baselines use stemming to merge word forms.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplepreprocess('The cats are running quickly!', {'the', 'are'})
  • Sample 2: short words keep their endingpreprocess('She sings, he sing; red beds fly.', {'she', 'he'})
  • Test 3: order of suffix rulespreprocess('boxes passed calmly agents', set())
  • Test 4: numbers and stopwordspreprocess('GPU 4090s is a beast', {'is', 'a'})