Text preprocessing in Python usually means a checklist: lowercase, tokenize, remove stop words, stem. Tutorials rarely measure whether each step helps. Here we test them on 2,000 real movie reviews (the Pang and Lee polarity dataset, 1,000 positive and 1,000 negative) and report vocabulary size and accuracy for each choice, so you can decide which steps earn their place.
Versions: scikit-learn 1.9.1, NLTK 3.10.4, pandas 3.0.5. Reviews average 746 words (median 696). The labelled sentiment task is the same one we use in sentiment analysis with Python; here the model is held fixed (TF-IDF plus logistic regression) and only the preprocessing changes.
Step 1: tokenization decides what a word is
A tokenizer splits text into units. A plain split() keeps punctuation glued to words; a regex does better but has its own choices:
import re
ex = "The movie wasn't GOOD... I've seen better, e.g. \"Jaws\" (1975)! 10/10 would NOT recommend :-("
print(ex.split())
print(re.findall(r"[a-z']+", ex.lower()))
print(re.findall(r"\b\w\w+\b", ex.lower()))Output:
['The', 'movie', "wasn't", 'GOOD...', "I've", 'seen', 'better,', 'e.g.', '"Jaws"', '(1975)!', '10/10', 'would', 'NOT', 'recommend', ':-(']
['the', 'movie', "wasn't", 'good', "i've", 'seen', 'better', 'e', 'g', 'jaws', 'would', 'not', 'recommend']
['the', 'movie', 'wasn', 'good', 've', 'seen', 'better', 'jaws', '1975', '10', '10', 'would', 'not', 'recommend']The default pattern in scikit-learn (the third line) splits “wasn’t” into “wasn” and drops “t”, and keeps “1975” and “10” as separate numbers. The emoticon disappears in both regex versions. None of this is wrong, but it is a decision.
Step 2: the corpus may already be clean
Before lowercasing anything, check whether it matters. In this dataset no review contains a capital letter (0 of 2,000), so lowercasing changed nothing: the vocabulary was 35,255 features with or without it. Always look at your own data first.
Step 3: stop words, and why they can hurt
scikit-learn’s English stop list has 318 words. On this corpus (1,303,953 tokens) they make up 50.3% of all tokens, so removing them halves the text. The catch is that the list includes negations:
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS, TfidfVectorizer
print([w for w in ["not", "no", "nor", "never", "n't", "cannot", "nothing"] if w in ENGLISH_STOP_WORDS])
v = TfidfVectorizer(ngram_range=(1, 2), min_df=2).fit(train_docs)
v2 = TfidfVectorizer(ngram_range=(1, 2), min_df=2, stop_words="english").fit(train_docs)
print("'not good' kept:", "not good" in v.vocabulary_, "| stop words removed:", "not good" in v2.vocabulary_)Output:
['not', 'no', 'nor', 'never', 'cannot', 'nothing']
'not good' kept: True | stop words removed: FalseWith the stop list applied, the bigram “not good” cannot exist, so a model cannot learn that it signals a negative review. For sentiment, remove stop words carefully or not at all.
Step 4: stemming merges words, sometimes wrongly
The Porter stemmer chops suffixes with rules, not a dictionary:
from nltk.stem import PorterStemmer
st = PorterStemmer()
print({w: st.stem(w) for w in ["running","runs","ran","better","studies","studying","movies","movie","argument","arguing","was"]})Output:
{'running': 'run', 'runs': 'run', 'ran': 'ran', 'better': 'better', 'studies': 'studi', 'studying': 'studi', 'movies': 'movi', 'movie': 'movi', 'argument': 'argument', 'arguing': 'argu', 'was': 'wa'}Good merges (running and runs, movies and movie), but “ran” stays apart, “argument” and “arguing” do not match, and “was” becomes “wa”. Across the whole corpus, 42,666 distinct words collapsed to 29,042 stems, yet the stem “gener” absorbed 19 different words including general, generally, generation and generic. Stemming also has to be applied inside your pipeline so it runs the same way at prediction time.
Step 5: what it did to accuracy
We ran each configuration with one stratified split (1,500 training and 500 test reviews) and logistic regression:
rows = {
"default tokens": dict(),
"keep single chars and apostrophes": dict(token_pattern=r"[A-Za-z0-9']+"),
"stop words removed": dict(stop_words="english"),
"min_df=2": dict(min_df=2),
"Porter stemming": dict(analyzer=stem_an),
"stemming + min_df=2": dict(analyzer=stem_an, min_df=2),
"bigrams": dict(ngram_range=(1, 2)),
"bigrams + min_df=2": dict(ngram_range=(1, 2), min_df=2),
}Output:
default tokens vocab 35,255 acc 0.836
keep single chars and apostrophes vocab 38,192 acc 0.832
stop words removed vocab 34,950 acc 0.83
min_df=2 vocab 20,967 acc 0.838
Porter stemming vocab 23,387 acc 0.842
stemming + min_df=2 vocab 14,398 acc 0.844
bigrams vocab 434,161 acc 0.828
bigrams + min_df=2 vocab 109,795 acc 0.848
The spread of accuracies is 0.828 to 0.848, about two points on a 500-review test set, where one review is 0.2 points and the standard error is roughly 1.6 points. That is not enough to rank the options, so we repeated four of them with 5-fold cross-validation on all 2,000 reviews:
Output:
default (lowercase, 2+ char tokens) 0.819 sd 0.01
stop words removed 0.826 sd 0.017
bigrams, min_df=2 0.817 sd 0.015
stemming + min_df=2 0.828 sd 0.011All four sit within one point of each other, and the fold-to-fold standard deviation (0.010 to 0.017) is as large as the gaps. On this task, preprocessing choices changed the vocabulary size a lot and the accuracy very little. The genuine payoff was a smaller, faster model: stemming plus min_df=2 used 14,398 features instead of 35,255 at the same accuracy. Different tasks, such as topic classification or search, may behave differently, so measure on yours with cross-validation rather than assuming.
A practical order of work
Look at raw text first; pick a tokenizer on purpose; set min_df to drop one-off words (15,874 of the 42,666 distinct words, or 37%, occur only once); keep negations; add stemming only if it shrinks the vocabulary without hurting validation scores; and put every step inside one scikit-learn pipeline so test data is processed identically. For messy tabular data the same principle applies in cleaning and preprocessing data with Python. The scikit-learn text feature extraction guide documents every option used above.
Frequently asked questions
Do I always need to remove stop words?
No. They were 50.3% of tokens here, but removing them did not improve accuracy and deleted negations such as “not”.
Stemming or lemmatization?
Lemmatization uses a dictionary and gives real words, but needs extra data downloads; we only tested stemming here.
What does min_df do?
It drops terms that appear in fewer than that many documents. min_df=2 cut the vocabulary from 35,255 to 20,967 here.
Does preprocessing matter for modern language models?
Transformer models come with their own tokenizers, so the manual steps above matter mainly for classic bag-of-words pipelines like this one. We did not test transformers.
