Expert: deep learning and AI · NLP, embeddings and large language models · topic 48 of 62 · 30 min
Working with text: tokens and cleaning
Explanation
Why text needs special handling
Customer reviews, support tickets, WhatsApp messages and news articles are text, not numbers. Before any model can use them, we must turn them into numbers. How we split and clean the text decides what the model can see. A support team in India may get "refund nahi mila, pls help!!" and "Refund not received" about the same problem; good NLP should treat them as close.
Tokens and tokenising
A token is one unit of text that the system treats as a piece. For classic NLP, tokens are usually words. Tokenising means splitting text into tokens. The simplest way, text.split(), breaks on spaces but leaves punctuation stuck to words ("help!!"). A regular expression gives more control. Modern language models use sub-word tokens instead (topic 4).
import re
text = "Don't panic! UPI-payment of Rs 500, done."
tokens = re.findall(r"[a-z0-9']+", text.lower())
print(tokens)Common cleaning steps
- Lowercasing: "Delivery" and "delivery" become one token. (Careful: it can merge "US" the country with "us".)
- Removing punctuation and extra spaces.
- Removing stop words: very common words such as "the", "is", "and" that carry little meaning for tasks like topic detection. For sentiment, keep negations like "not"!
- Stemming: chopping word endings with simple rules ("delivered", "delivering" → "deliv"). Fast but crude.
- Lemmatisation: turning words into their dictionary form using vocabulary and grammar ("better" → "good", "was" → "be"). More accurate, slower. Libraries such as NLTK and spaCy provide both.
Counting words
Once text is tokenised, counting is easy with collections.Counter. Word counts already answer useful questions: which complaints are most frequent this week, which product features customers mention most. Sort by count, and break ties alphabetically so results are repeatable.
from collections import Counter
tickets = "late delivery. refund please. delivery was late again"
counts = Counter(tickets.replace(".", "").split())
print(counts.most_common(2))Indian-language challenges
- Many scripts: Devanagari, Tamil, Bengali, Telugu and more, each with its own rules for combining characters.
- Code-mixing: Hindi and English in one sentence ("kal meeting cancel hai").
- Transliteration: Hindi written in Latin letters with no fixed spelling ("nahi", "nahin", "nai").
- Fewer labelled datasets than English, although open resources such as AI4Bharat's models and Bhashini, the government's language platform, are growing.
Common mistakes
- Removing "not" as a stop word in sentiment tasks, which turns "not good" into "good".
- Applying English-only rules (like an English stop-word list or stemmer) to Hindi or mixed text.
- Cleaning the training data one way and live data another way. Fix: one cleaning function used everywhere.
- Splitting on spaces only, leaving "late." and "late" as different tokens.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Working with text: tokens and cleaning · 1/6
NLP means making computers work with human language. First we turn text into tokens.
Prefer a video by a teacher? Find free videos on “NLP text preprocessing tokenization stop words stemming lemmatization python” on YouTube ↗
In real life: What are customers complaining about?
A food-delivery support team receives thousands of chat messages a day. A simple script lowercases each message, tokenises it, removes stop words (but keeps "not" and "no"), and counts tokens per day. A sudden jump in "cold", "spilled" or "missing" for one city alerts the operations team within hours, long before monthly reports would.
Practice (0/3 done)
Write tokenize(text) that lowercases the text and returns re.findall(r"[a-z0-9']+", lowered): words made of letters a–z, digits and apostrophes.
Write top_words(text, k, stop_words) that tokenises with the same rule (lowercase, re.findall(r"[a-z0-9']+", ...)), drops any token in stop_words, counts the rest and returns the k most common as a list of (word, count) tuples, sorted by count (highest first) and then by word A→Z.
Write remove_stopwords(tokens, stop_words, keep) that removes tokens found in stop_words EXCEPT those in keep (for example keep negations like "not" for sentiment). Keep the order.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Bag of words, TF-IDF and text classificationNLP, embeddings and large language models · same module
- Embeddings and cosine similarityNLP, embeddings and large language models · same module
- How large language models workNLP, embeddings and large language models · same module
- String processingPython Programming · Working with data
- Indian-English word choices and natural fixesSpoken English: Zero to Fluent · Sound natural: phrasal verbs, idioms and Indian-English fixes
- What programming and Python arePython Programming · First steps in Python
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What is tokenising?
Answer: Splitting text into units such as words
Tokens are the pieces a model works with.
For sentiment analysis, why is removing "not" dangerous?
Answer: "not good" becomes "good", flipping the meaning
Negations carry crucial meaning for sentiment.
Which is lemmatisation?
Answer: "running" → "run" using vocabulary and grammar, and "better" → "good"
Lemmatisation finds the dictionary form; stemming just chops endings.
What is code-mixing?
Answer: Using two languages in one sentence, such as Hindi and English
It is very common in Indian social media and chat.
Why lowercase text before counting words?
Answer: So "Refund" and "refund" are counted as the same word
Otherwise the counts are split across spellings.
What is "a,b,,c".split(",")?Related
Answer: ["a", "b", "", "c"]
Two commas in a row leave an empty piece "" between them.
From String processing
You need the same extracted invoice fields every time. Which temperature setting fits best?Related
Answer: Low, near 0
Low temperature gives focused, repeatable output.
A date column has "05/01/2025" in Indian style. What should you do?Related
Answer: Pass format="%d/%m/%Y" explicitly
Guessing may read it as May 1. An explicit format avoids the mix-up.
From Cleaning messy data
Which word should replace "updation" in an international email?Related
Answer: an update
"Updation" is common in India but not used abroad. Say "an update" or "updating" (and "upgrade", not "upgradation").
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 4 more topics in “NLP, embeddings and large language models” before its exam: Bag of words, TF-IDF and text classification, Embeddings and cosine similarity, How large language models work, Prompting well.
- Module 10 exam: NLP, embeddings and large language models · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Building with generative AI, and MLOps. 62 topics left in the course before the final exam.