1. Understand the Goal: The user wants a Python script to "clean and normalize text data." This is a common NLP preprocessing task.
Identify Key Requirements: What does "cleaning and normalizing" usually entail?
Lowercasing: Standardizing case.
Noise Removal: HTML tags, URLs, emails, special characters, punctuation, numbers, whitespace.
Normalization:
Tokenization (splitting into words).
Stopword removal (removing "the", "is", etc.).
Stemming (chopping off ends) vs. Lemmatization (getting root form - better but slower).
Handling contractions (expanding "don't" to "do not").
Unicode normalization (NFKD, etc.).
Emoji/Emoticon handling (remove or translate to text).
Select Tools:
Standard Library:re (regex) is essential for pattern matching. string for punctuation. unicodedata for unicode.
Third-party Libraries:
nltk: The classic choice. Good for stopwords, lemmatization, stemming.
spacy: More modern, robust, but heavier.
textblob: Simpler, but maybe less control.
contractions: Specific library for expanding contractions (optional but nice).
Decision: I'll use nltk because it's widely taught and explicit. I will also use standard regex for heavy lifting. I won't require too many niche libraries to keep it runnable.
Structure the Code:
Create a class or a set of functions. A class TextCleaner is often cleaner for holding state (like loading NLTK data once) and allowing configuration.
Refining the scope: I shouldn't make it too complex (like handling slang "gr8" -> "great" requires a specific mapper). I will stick to standard operations.
Writing the Code (Iterative):
Imports:re, string, nltk, pandas (maybe just for demo, or stick to lists). Let's stick to plain Python + NLTK.
NLTK Downloads: Need to remind user to download punkt, stopwords, wordnet.
Implementation Details:
HTML:re.sub(r'<.*?>', '', text)
URLs:re.sub(r'https?://\S+|www\.\S+', '', text)
Emojis: Use a complex regex pattern found in standard libs (or just re.sub(r'[^\x00-\x7F]+', '', text) for non-ASCII, but that kills accents. Better to use a specific emoji regex pattern).
Lemmatizer:WordNetLemmatizer. Note: It needs POS tags for best results, but for a simple script, we can skip POS tagging or default to nouns/verbs. I'll keep it simple.
Refining the Solution:
I will create a modular TextPreprocessor class. This allows users to toggle steps (e.g., keep punctuation if they want).
Features to include:
Lowercasing.
Unicode Normalization (NFKD is good for accents).
Removing URLs/HTML.
Expanding contractions (I'll write a simple regex dict for common ones to avoid an extra dependency, or just ignore it for brevity. Actually, contractions is a pip package. Let's stick to regex for portability).
Removing Punctuation/Digits.
Stopword removal.
Lemmatization.
Code Construction (Mental Draft):
python
import re
import string
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
class TextCleaner:
def __init__(self):
# init stop words and lemmatizer
pass
def clean(self, text):
# apply steps
return text
Adding Explanations:
Explain why each step is done.
Regex for pattern matching.
Stopwords for reducing noise.
Lemmatization for reducing dimensionality.
Final Polish:
Add error handling (if input is None).
Add a usage example.
Add comments.
Self-Correction during drafting:
Issue: Lemmatization without POS tagging is weak.
Fix: I'll mention it in comments, but to keep the script simple and dependency-low (avoiding averaged_perceptron_tagger complexities), I will just use the default lemmatizer.
Issue: Removing emojis.
Fix: Include a robust regex for emojis.
Final Output Generation: (This matches the provided good response). I will organize it by creating a flexible class.
Step 1: Define dependencies (pip install nltk).
Step 2: The script.
Step 3: Example usage.
Let's write the code now. I will focus on readability and modularity.
Regex patterns:
URL: https?://\S+|www\.\S+
HTML: <.*?>
Emojis: A specific pattern involving ranges \U0001F600-\U0001F64F etc.
Punctuation: string.punctuation or regex [^\w\s].
Contractions:
Writing a full dictionary is too long for a snippet. I will skip complex contraction expansion unless requested, or use a small function. Actually, standard text cleaning often skips this unless strictly necessary for embeddings. I'll focus on the core NLP pipeline.
Stopwords:
Ensure language support (default to English).
Lemmatizer:WordNetLemmatizer.
Let's assemble.
Here is a comprehensive, modular Python script to clean and normalize text data.
This solution uses the NLTK (Natural Language Toolkit) library for advanced linguistic operations (like stemming and stopword removal) and standard Python Regular Expressions (re) for pattern cleaning.
Prerequisites
You will need to install nltk:
bash
pip install nltk
The Python Script
python
Explanation of Steps
Lowercasing: Ensures "Apple" and "apple" are treated as the same word.
Removing URLs/HTML: Web data often contains links (http...) or markup (<div>) that adds noise to analysis.
Removing Emojis/Unicode: While sentimental analysis might use emojis, general text processing usually removes them to focus on language.
Removing Punctuation & Numbers: Punctuation rarely adds value to topic modeling, and numbers can create sparse data features (unless specific dates/amounts are relevant).
Tokenization: Splits the sentence into individual words (tokens).
Stopword Removal: Filters out common words like "the", "is", "and" that occur frequently but carry little unique meaning.
Lemmatization: Converts words to their dictionary form (e.g., "better" → "good", "running" → "run"). This is generally more accurate than "Stemming" (which just chops off word endings).
import re
import string
import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
# Download necessary NLTK data files (run once)
try:
nltk.data.find('tokenizers/punkt')
nltk.data.find('corpora/stopwords')
nltk.data.find('corpora/wordnet')
except LookupError:
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('wordnet')
nltk.download('omw-1.4') # Optional but recommended for lemmatizer
class TextCleaner:
def __init__(self, language='english'):
self.stop_words = set(stopwords.words(language))
self.lemmatizer = WordNetLemmatizer()
def to_lowercase(self, text):
"""Convert text to lowercase."""
return text.lower()
def remove_urls(self, text):
"""Remove URLs (http/https/www)."""
pattern = re.compile(r'https?://\S+|www\.\S+')
return pattern.sub(r'', text)
def remove_html_tags(self, text):
"""Remove HTML tags."""
pattern = re.compile(r'<.*?>')
return pattern.sub(r'', text)
def remove_emojis(self, text):
"""Remove emojis and special unicode characters."""
# This regex pattern covers most common emojis
emoji_pattern = re.compile("["
u"\U0001F600-\U0001F64F" # emoticons
u"\U0001F300-\U0001F5FF" # symbols & pictographs
u"\U0001F680-\U0001F6FF" # transport & map symbols
u"\U0001F1E0-\U0001F1FF" # flags (iOS)
u"\U00002702-\U000027B0"
u"\U000024C2-\U0001F251"
"]+", flags=re.UNICODE)
return emoji_pattern.sub(r'', text)
def remove_punctuation(self, text):
"""Remove punctuation marks."""
return text.translate(str.maketrans('', '', string.punctuation))
def remove_numbers(self, text):
"""Remove digits."""
return re.sub(r'\d+', '', text)
def remove_stopwords(self, tokenized_text):
"""Remove common stopwords (requires tokenized list)."""
return [word for word in tokenized_text if word not in self.stop_words]
def lemmatize_words(self, tokenized_text):
"""Convert words to their base form (e.g., running -> run)."""
return [self.lemmatizer.lemmatize(word) for word in tokenized_text]
def clean_text(self, text, remove_stopwords=True, lemmatize=True, remove_nums=True):
"""
Master function to apply all cleaning steps.
Args:
text (str): The raw text string.
remove_stopwords (bool): Whether to drop stopwords.
lemmatize (bool): Whether to lemmatize words.
remove_nums (bool): Whether to remove numbers.
Returns:
str: The cleaned, normalized text string.
"""
# 1. Basic Cleaning (String level)
text = self.to_lowercase(text)
text = self.remove_urls(text)
text = self.remove_html_tags(text)
text = self.remove_emojis(text)
if remove_nums:
text = self.remove_numbers(text)
text = self.remove_punctuation(text)
# 2. Fix whitespaces
text = " ".join(text.split())
# 3. Tokenization
tokens = word_tokenize(text)
# 4. Normalization (List level)
if remove_stopwords:
tokens = self.remove_stopwords(tokens)
if lemmatize:
tokens = self.lemmatize_words(tokens)
# 5. Join back to string
return " ".join(tokens)
# --- Usage Example ---
if __name__ == "__main__":
raw_text = """
<p>Hello!!!</p> This is a Sample TEXT with HTML tags.
I love NLP! It's fascinating... 100%.
Check out https://google.com for more info.
Running, ran, runs -> run.
"""
cleaner = TextCleaner()
print("--- Original Text ---")
print(raw_text)
cleaned = cleaner.clean_text(raw_text)
print("\n--- Cleaned & Normalized Text ---")
print(cleaned)