Text Processing
Before running an NLP model, text must be cleaned and preprocessed. Good preprocessing can significantly improve model performance.
10 min•By Priygop Team•Updated 2026
Common Text Preprocessing Steps
- Lowercasing: convert all text to lowercase so 'Dog' and 'dog' are treated the same
- Removing punctuation: remove characters like ! ? , . that do not carry meaning for many tasks
- Removing stopwords: remove very common words like 'the', 'is', 'a' that add little information
- Stemming: reduce words to their root (running, runs, ran all become 'run')
- Lemmatization: similar to stemming but uses proper linguistic roots (better, good -> good)
- Removing extra spaces and special characters
- Not all steps apply to all tasks: for sentiment analysis, punctuation like '!!!' carries meaning
Text Preprocessing in Code
Text Preprocessing in Code
# Common text preprocessing steps
import re
def preprocess_text(text, lowercase=True, remove_punctuation=True,
remove_stopwords=True, stopwords=None):
"""Apply common text preprocessing steps."""
if stopwords is None:
stopwords = {"the", "a", "an", "is", "it", "in", "on", "at", "to", "was", "for"}
# Step 1: lowercase
if lowercase:
text = text.lower()
# Step 2: remove punctuation
if remove_punctuation:
text = re.sub(r"[^\w\s]", "", text)
# Step 3: tokenize (split into words)
words = text.split()
# Step 4: remove stopwords
if remove_stopwords:
words = [w for w in words if w not in stopwords]
return words
# Test preprocessing
raw_texts = [
"The movie was absolutely fantastic! I loved every second.",
"I hated it, what a waste of time!!!",
"It's an OK film, nothing special.",
]
print("Text Preprocessing Results:")
print()
for text in raw_texts:
tokens = preprocess_text(text)
print(f" Original: '{text}'")
print(f" Processed: {tokens}")
print()Diagram
Loading diagram…
Deep Learning ⊂ Machine Learning ⊂ Artificial Intelligence
Try It Yourself
Try It YourselfHTML
HTML Editor
✓ ValidTab = 2 spaces
HTML|22 lines|636 chars|✓ Valid syntax
UTF-8
Key Takeaways
- Before running an NLP model, text must be cleaned and preprocessed.
- Lowercasing: convert all text to lowercase so 'Dog' and 'dog' are treated the same
- Removing punctuation: remove characters like ! ? , . that do not carry meaning for many tasks
- Removing stopwords: remove very common words like 'the', 'is', 'a' that add little information