Welcome to Module Eight! In previous modules, we learned how to clean numbers, dates, and simple text. But sometimes text is very messyβit has extra spaces, strange characters, or inconsistent patterns. For advanced text cleaning, we use a powerful tool called Regular Expressions (or "regex" for short). Regex helps us find and fix patterns in text. By the end of this module, you will be able to clean even the messiest text data. Let's begin!
After this module, you will be able to:
A company in Nigeria had customer comments. They wanted to find all phone numbers in the comments. But the phone numbers were written in many waysβsome with spaces, some with dashes, some with country codes. It was impossible to find them manually.
A data analyst used regular expressions. She wrote a pattern that matched phone numbers in any formatβwith or without spaces, with or without country code. The regex found all the phone numbers instantly.
This module teaches you how to use regular expressions to clean messy text like a pro.
Definition: Regular expressions (regex) are patterns used to match and manipulate text.
Why it is important: Regex allows you to find, extract, or replace text based on patterns.
Simple explanation: Think of regex as a super-powered search. It can find text that follows a pattern, like all email addresses or phone numbers.
Real-life example: A company uses regex to extract all email addresses from a customer list.
School example: A student uses regex to find all dates in a document.
Home example: You use regex to find all amounts in your budget.
Nigerian example: A business uses regex to extract phone numbers from customer comments.
Illustration:
Text: "My phone is 080-123-4567"
Regex pattern: \d{3}-\d{3}-\d{4}
Found: 080-123-4567
Mini summary: Regex is a powerful tool to find patterns in text.
Definition: The re module is Python's built-in library for regular expressions.
Why it is important: You need to import re to use regex in Python.
Simple explanation: You write: import re
Real-life example: A data analyst imports re before using regex.
School example: A student imports re for a project.
Home example: You import re to clean your data.
Nigerian example: A developer imports re for text processing.
Illustration:
import re
Mini summary: Import re to use regular expressions.
Definition: Basic regex patterns include characters like \d for digits, \w for word characters, and \s for spaces.
Why it is important: These patterns help you match different types of characters.
Simple explanation: \d matches any digit (0-9). \w matches any letter, digit, or underscore. \s matches any space.
Real-life example: You use \d to find all numbers in a text.
School example: You use \w to find all words.
Home example: You use \s to find spaces.
Nigerian example: You use \d to find phone digits.
Illustration:
\d -> matches any digit
\w -> matches any word character
\s -> matches any whitespace
Mini summary: Basic patterns match digits, words, and spaces.
Definition: Quantifiers specify how many times a pattern should appearβlike +, *, and ?.
Why it is important: They help you match patterns of varying length.
Simple explanation: + means "one or more", * means "zero or more", ? means "zero or one".
Real-life example: You use \d+ to match one or more digits.
School example: You use \s* to match zero or more spaces.
Home example: You use \w? to match zero or one word character.
Nigerian example: You use \d{3} to match exactly 3 digits.
Illustration:
+ -> one or more
* -> zero or more
? -> zero or one
{3} -> exactly 3
{2,4} -> 2 to 4
Mini summary: Quantifiers control how many times a pattern appears.
Definition: Special characters like ., *, +, ?, etc., have special meanings in regex. To match them literally, you need to escape them with a backslash (\).
Why it is important: If you want to match a period (.) as a period, you must escape it.
Simple explanation: To match a literal dot, you use \.
Real-life example: You use \. to match a period in a file name.
School example: You use \* to match an asterisk.
Home example: You use \? to match a question mark.
Nigerian example: You use \. to match a decimal point.
Illustration:
. -> any character (except newline)
\. -> a literal period
* -> zero or more
\* -> a literal asterisk
Mini summary: Escape special characters to match them literally.
Definition: re.search() searches for a pattern in a string and returns the first match.
Why it is important: It's useful when you just need to know if a pattern exists.
Simple explanation: re.search(pattern, text) returns a match object if found, else None.
Real-life example: You check if a text contains an email address.
School example: You check if a document contains a date.
Home example: You check if a note contains a phone number.
Nigerian example: You check if a comment contains a phone number.
Illustration:
result = re.search(r'\d{3}-\d{3}-\d{4}', text)
if result:
print("Found:", result.group())
Mini summary: re.search() finds the first match of a pattern.
Definition: re.findall() returns all non-overlapping matches of a pattern in a string.
Why it is important: It's useful when you want to extract all occurrences of a pattern.
Simple explanation: re.findall(pattern, text) returns a list of all matches.
Real-life example: You extract all email addresses from a text.
School example: You extract all dates from a document.
Home example: You extract all numbers from a budget.
Nigerian example: You extract all phone numbers from customer comments.
Illustration:
emails = re.findall(r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}', text)
Mini summary: re.findall() returns all matches.
Definition: re.sub() replaces occurrences of a pattern with a replacement string.
Why it is important: It's useful for cleaning text by removing or replacing unwanted patterns.
Simple explanation: re.sub(pattern, replacement, text) returns the text with replacements.
Real-life example: You remove extra spaces from text.
School example: You replace abbreviations with full words.
Home example: You remove special characters from a string.
Nigerian example: You replace inconsistent date formats.
Illustration:
clean_text = re.sub(r'\s+', ' ', text) # Replace multiple spaces with one
Mini summary: re.sub() replaces patterns in text.
Definition: re.split() splits a string by the occurrences of a pattern.
Why it is important: It's useful for breaking text into parts based on a delimiter.
Simple explanation: re.split(pattern, text) returns a list of split parts.
Real-life example: You split a sentence by commas.
School example: You split a CSV line by commas.
Home example: You split a grocery list by commas.
Nigerian example: You split customer data by semicolons.
Illustration:
parts = re.split(r',\s*', text)
Mini summary: re.split() splits text by a pattern.
Definition: You can use regex in Pandas with methods like str.contains(), str.extract(), and str.replace().
Why it is important: It allows you to clean text data in DataFrames efficiently.
Simple explanation: You use data['col'].str.contains(pattern) to find rows matching a pattern.
Real-life example: You extract all phone numbers from a customer column.
School example: You extract all student IDs.
Home example: You extract all amounts from a budget column.
Nigerian example: You extract all email addresses from a customer list.
Illustration:
data['phone'] = data['comment'].str.extract(r'(\d{3}-\d{3}-\d{4})')
Mini summary: Use regex in Pandas with str methods.
Definition: Common tasks include removing extra spaces, extracting phone numbers, cleaning emails, and removing special characters.
Why it is important: These are the most frequent cleaning tasks in real-world data.
Simple explanation: You use regex to find and fix these common problems.
Real-life example: A company removes extra spaces from customer names.
School example: A student extracts dates from a text.
Home example: You remove special characters from a list.
Nigerian example: A business extracts phone numbers from comments.
Illustration:
# Remove extra spaces
data['text'] = data['text'].str.replace(r'\s+', ' ', regex=True)
# Extract phone numbers
data['phone'] = data['text'].str.extract(r'(\d{3}-\d{3}-\d{4})')
Mini summary: Regex handles common text cleaning tasks.
Definition: Complex patterns combine multiple elements to match intricate text patterns.
Why it is important: Some patterns are not simpleβlike matching emails or URLs.
Simple explanation: You combine characters, quantifiers, and groups to build a pattern.
Real-life example: A pattern to match Nigerian phone numbers.
School example: A pattern to match student IDs.
Home example: A pattern to match dates.
Nigerian example: A pattern to match Lagos addresses.
Illustration:
# Nigerian phone number pattern
pattern = r'(0|\+234)[7-9][0-9]{9}'
Mini summary: Complex patterns combine many elements.
Definition: Practice applying regex to clean messy text.
Why it is important: Practice helps you master regex.
Simple explanation: You take a messy text column and apply regex to clean it.
Real-life example: A data analyst cleans customer comments.
School example: A student cleans a text dataset.
Home example: You clean your own text data.
Nigerian example: A student cleans local text data.
Illustration:
data['clean_text'] = data['text'].str.replace(r'[^a-zA-Z0-9\s]', '', regex=True)
Mini summary: Practice regex on real text data.
Definition: You can use regex to validate text patterns, like checking if a string is a valid email or phone number.
Why it is important: It ensures text data meets expected formats.
Simple explanation: You check if a string matches a pattern.
Real-life example: A company validates email addresses.
School example: A student validates student IDs.
Home example: You validate phone numbers.
Nigerian example: A business validates NIN numbers.
Illustration:
def is_valid_email(email):
pattern = r'[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}'
return re.match(pattern, email) is not None
Mini summary: Regex validates text patterns.
Definition: A project where you apply regex to clean a text dataset.
Why it is important: It gives you real-world experience.
Simple explanation: You find a messy text dataset and clean it using regex.
Real-life example: A data analyst cleans customer comments.
School example: A student completes a class project.
Home example: You clean your own text data.
Nigerian example: A student uses a Nigerian text dataset.
Illustration:
Step 1: Load text data.
Step 2: Identify patterns.
Step 3: Apply regex to clean.
Step 4: Validate results.
Mini summary: Apply regex to a real text cleaning project.
How to Clean Text with Regex in 6 Steps:
This module introduces regular expressions, a powerful but sometimes tricky topic. Teachers should start with simple patterns and gradually introduce complexity. Use plenty of examples and practice exercises. Emphasize that regex is a tool for pattern matching, and it's okay to start with simple patterns.
Parents can help children understand regex by using everyday examplesβlike searching for a specific word in a book or finding numbers in a text. Encourage children to think about patterns in text and how they can be used to clean data.
Regex Matching Process
Text -> Pattern -> Match? -> Yes -> Extract/Replace
|
No
|
No Action
Common Regex Patterns
\d -> digit
\w -> word character
\s -> whitespace
. -> any character
+ -> one or more
* -> zero or more
? -> zero or one
{3} -> exactly 3
Regex Methods
| Method | Purpose |
|---|---|
| re.search() | Find first match |
| re.findall() | Find all matches |
| re.sub() | Replace matches |
| re.split() | Split text |
Without Regex vs With Regex
| Without Regex | With Regex |
|---|---|
| Manual string methods | Powerful pattern matching |
| Limited to simple tasks | Handles complex patterns |
| Slower for large data | Efficient for large data |
In Module Eight, we learned about regular expressions (regex) for advanced text cleaning. We discovered what regex is and how to use it to find patterns in text. We learned basic patterns, quantifiers, and how to escape special characters. We used re.search(), re.findall(), re.sub(), and re.split() to manipulate text. We also applied regex in Pandas using str methods. We practiced common text cleaning tasks like removing extra spaces, extracting phone numbers, and validating email addresses. These skills are essential for cleaning messy text data. You are now a text-cleaning expert!
Match the term with its description:
| Term | Description |
|---|---|
| 1. re.search() | A. Finds all matches |
| 2. re.findall() | B. Replaces matches |
| 3. re.sub() | C. Finds first match |
| 4. re.split() | D. Splits text |
| 5. \d | E. Matches a digit |
Answers: 1-C, 2-A, 3-B, 4-D, 5-E
Scenario 1: You have a dataset of customer comments. Extract all phone numbers using regex.
Scenario 2: You have a dataset of addresses. Clean the addresses by removing extra spaces and special characters.
Scenario 3: You have a dataset of emails. Validate that all emails are in the correct format.
In groups, find a messy text dataset. Identify common patterns (phone numbers, emails, dates). Write regex patterns to extract and clean these patterns. Present your results to the class.
Write a Python script that uses regex to clean a text column in a dataset. Include extraction, replacement, and validation. Test it on a sample dataset. Write a short report on your results.
Create a "Text Cleaning Tool" that uses regex to clean a text column. Include functions to remove extra spaces, extract phone numbers, and validate emails. Apply it to a real dataset and show the results.
Find a messy text dataset (e.g., customer comments, social media posts). Clean it using regex. Write a report on your cleaning process, including the patterns you used and the results.
Write a regex pattern to match Nigerian phone numbers in all common formats (with spaces, dashes, country code). Test it on a large text dataset and extract all phone numbers.
Answers to the Multiple Choice Questions are already provided above. For other exercises, refer to the lessons and key vocabulary.
In Module Nine, we will learn about data integration and merging from multiple sources. You will learn how to combine data from different files and databases. Get ready for the final module!
End of Module Eight β You are now a regex master!