Rana Maninder Singh
Lesson 12 of 12Data Analysis with Python

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

ResourceLink
PreviousPlotly
NextWhat is statistics?
PrerequisitesPandas basics, Plotly
Time~55 minutes
What you needpip 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.

StepPurpose
CleanFix casing, remove noise
TokenizeSplit into words
Remove stopwordsDrop "the", "is", "and"
VectorizeNumbers per document (TF-IDF, embeddings)
ModelClassify 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.

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:


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)) # probabilities

Section 6 — Connection to deep learning

Classical (this lesson)Deep learning (dl6)
TF-IDF bag of wordsWord embeddings (Word2Vec, learned)
Sparse, interpretableDense vectors, context-aware
Works on small dataShines on large text corpora
Logistic regression on TF-IDFLSTM / 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

  1. Clean a list of 10 customer reviews; tokenize and drop stopwords.
  2. Build a TF-IDF matrix; print top 5 feature names.
  3. 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.