NLP Basics — Text Cleaning, TF-IDF & Sentiment
Lesson opener
In one line: Clean raw text - lowercasing, punctuation, tokenization.
Why it matters: This shows up at work when you need to clean raw text - lowercasing, punctuation, tokenization.
Before this lesson: Pandas basics / Plotly
Before you start
| Resource | Link |
|---|---|
| Previous | Plotly |
| Next | What is statistics? |
| Prerequisites | Pandas basics, Plotly |
| Time | ~55 minutes |
| What you need | pip install pandas scikit-learn (no deep learning required yet) |
What you will learn
- Clean raw text — lowercasing, punctuation, tokenization
- Remove stopwords and why they matter
- Build a TF-IDF matrix for document features
- Run basic sentiment analysis with sklearn
- How this connects to text embeddings in deep learning
This lesson is the classical NLP bridge before neural nets. If you can explain TF-IDF, dl6 embeddings will make more sense.
Section 1 — Why text needs its own pipeline
Plain English:
Customer reviews, support tickets, and NPS comments are not numbers. You cannot df["review"].mean(). NLP turns messy sentences into features ML models can use.
| Step | Purpose |
|---|---|
| Clean | Fix casing, remove noise |
| Tokenize | Split into words |
| Remove stopwords | Drop "the", "is", "and" |
| Vectorize | Numbers per document (TF-IDF, embeddings) |
| Model | Classify sentiment, topic, urgency |
Workplace example (Hyderabad SaaS): 2,000 support tickets last month. TF-IDF + logistic regression flags "billing" and "refund" urgency before a human reads every ticket.
Section 2 — Text cleaning
import re
import pandas as pd
reviews = pd.DataFrame({
"review_id": [1, 2, 3],
"text": [
" LOVE this product!!! Best purchase ever. ",
"Terrible service. Will NOT recommend.",
"OK quality, delivery was late though.",
],
})
def clean_text(s: str) -> str:
s = s.lower().strip()
s = re.sub(r"[^a-z\s]", " ", s) # keep letters and spaces
s = re.sub(r"\s+", " ", s) # collapse whitespace
return s
reviews["clean"] = reviews["text"].apply(clean_text)
print(reviews["clean"])Section 3 — Tokenization and stopwords
from sklearn.feature_extraction.text import ENGLISH_STOP_WORDS
def tokenize(s: str) -> list[str]:
return [w for w in s.split() if w not in ENGLISH_STOP_WORDS and len(w) > 2]
reviews["tokens"] = reviews["clean"].apply(tokenize)
print(reviews["tokens"])Token = one word (roughly). Stopwords = common words with little meaning ("the", "is"). Removing them helps models focus on "refund", "broken", "excellent".
Section 4 — TF-IDF
TF-IDF (Term Frequency × Inverse Document Frequency) scores how important a word is in one document compared to the whole corpus.
- TF — word appears often in this document → higher score
- IDF — word appears in every document → lower score (e.g. "product" everywhere)
from sklearn.feature_extraction.text import TfidfVectorizer
corpus = reviews["clean"].tolist()
vectorizer = TfidfVectorizer(
stop_words="english",
max_features=100,
ngram_range=(1, 2), # unigrams + bigrams
)
X = vectorizer.fit_transform(corpus)
print(X.shape) # (3 documents, N features)
print(vectorizer.get_feature_names_out()[:10])Breaking it down:
fit_transform(corpus)— learn vocabulary + build sparse matrix- Each row = one document; each column = one term's TF-IDF weight
- Ready for sklearn classifiers — same API as numeric features
Section 5 — Basic sentiment analysis
Label reviews manually (or use existing labels), then train:
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import classification_report
labels = [1, 0, 0] # 1=positive, 0=negative (toy example)
X_train, X_test, y_train, y_test = train_test_split(
X, labels, test_size=0.33, random_state=42
)
model = LogisticRegression(max_iter=1000)
model.fit(X_train, y_train)
pred = model.predict(X_test)
print(classification_report(y_test, pred))New review prediction:
new_review = clean_text("Amazing support team, fixed my issue quickly!")
X_new = vectorizer.transform([new_review])
print(model.predict(X_new)) # [1]
print(model.predict_proba(X_new)) # probabilitiesSection 6 — Connection to deep learning
| Classical (this lesson) | Deep learning (dl6) |
|---|---|
| TF-IDF bag of words | Word embeddings (Word2Vec, learned) |
| Sparse, interpretable | Dense vectors, context-aware |
| Works on small data | Shines on large text corpora |
| Logistic regression on TF-IDF | LSTM / Transformers |
You are not replacing TF-IDF overnight in production. Many teams still use TF-IDF + logistic regression for ticket routing because it is fast, cheap, and explainable.
Practice
- Clean a list of 10 customer reviews; tokenize and drop stopwords.
- Build a TF-IDF matrix; print top 5 feature names.
- Train sentiment on a small labelled set; predict one new sentence.
Checklist
- [ ] Can you clean text with lowercase, regex, and strip?
- [ ] Do you know what tokenization and stopwords are?
- [ ] Can you build a TF-IDF matrix with
TfidfVectorizer? - [ ] Can you train a classifier on text features and predict a new review?
- [ ] Can you explain how TF-IDF relates to embeddings in dl6?
What's next
What is a neural network? — when tabular ML and bag-of-words are not enough.