Hiring Partners
Segilola Resources Operating LimitedTaviatech TechnologiesFCMBMTN NigeriaAdvans La Fayette Microfinance BankAboki AfricaFirst Bank of NigeriaOPay
← Phyton For Data Cleaning Β· Lesson 9 of 9

Module Eight

πŸ“– Every lesson in this course is free to read right here, no account needed. Create a free account to track your progress, take the exam, and earn your certificate.
9
Module 8: Python for Data Cleaning – Advanced Text Cleaning with Regular Expressions

πŸ“˜ Module Eight: Python for Data Cleaning – Advanced Text Cleaning with Regular Expressions

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!

🎯 Learning Objectives

After this module, you will be able to:

  • Explain what regular expressions are.
  • Use common regex patterns to find and clean text.
  • Apply regex to extract, replace, and remove text.
  • Clean text data using regex in Pandas.
  • Apply these techniques to real datasets.

πŸ“– Warm-up Story: The Messy Customer Comments

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.

πŸ“š Main Lessons

Lesson 1: What are Regular Expressions?

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.

Lesson 2: Importing the re Module

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.

Lesson 3: Basic Regex Patterns

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.

Lesson 4: Quantifiers – How Many?

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.

Lesson 5: Special Characters and Escaping

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.

Lesson 6: Searching with re.search()

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.

Lesson 7: Finding All Matches with re.findall()

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.

Lesson 8: Replacing Text with re.sub()

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.

Lesson 9: Splitting Text with re.split()

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.

Lesson 10: Using Regex in Pandas

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.

Lesson 11: Common Text Cleaning Tasks with Regex

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.

Lesson 12: Writing Complex Regex Patterns

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.

Lesson 13: Practice Cleaning Text with Regex

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.

Lesson 14: Validating Text with Regex

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.

Lesson 15: Your Text Cleaning Project

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.

πŸ”‘ Key Vocabulary

  • Regular Expression (regex): A pattern to match text.
  • re: Python's regular expression module.
  • Pattern: The regex string used to match text.
  • Quantifier: Specifies how many times a pattern appears.
  • Escape: Using a backslash to match special characters.
  • search(): Finds the first match.
  • findall(): Finds all matches.
  • sub(): Replaces matches.
  • split(): Splits text by pattern.
  • Valid: Data that follows a pattern.

πŸ’‘ Important Concepts

  • Regex is for pattern matching in text.
  • Import re to use regex.
  • Use quantifiers for repetition.
  • Escape special characters to match them.
  • Use search(), findall(), sub(), split().
  • Use regex in Pandas with str methods.
  • Regex is used for cleaning, extracting, and validating.

πŸ“ Step-by-Step Explanations

How to Clean Text with Regex in 6 Steps:

  1. Import re: import re
  2. Define Pattern: pattern = r'...'
  3. Search or Extract: re.search(pattern, text)
  4. Replace: re.sub(pattern, replacement, text)
  5. Apply to DataFrame: data['col'].str.replace(pattern, ...)
  6. Validate: Check if text matches pattern.

🌍 Real-life Examples

  • A company extracts email addresses from text.
  • A school cleans student comments.
  • A hospital extracts patient IDs.
  • A bank validates account numbers.

πŸ‡³πŸ‡¬ Nigerian Examples

  • A Nigerian business extracts phone numbers from customer comments.
  • A Nigerian school validates student IDs.
  • A Nigerian hospital validates NIN numbers.
  • A Nigerian government cleans address data.

🎈 Fun Examples Children Relate To

  • Extract all video game titles from a text.
  • Clean a list of your favorite movies.
  • Extract all dates from your calendar.
  • Clean your to-do list by removing special characters.

🏠 Everyday Examples

  • Remove extra spaces from your notes.
  • Extract phone numbers from your contacts.
  • Clean a grocery list.
  • Validate email addresses.

πŸ§‘β€πŸ« Teacher Notes

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.

πŸ‘ͺ Parent Tips

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.

🌟 Interesting Facts

  • Regular expressions were invented in the 1950s.
  • Regex is used in almost every programming language.
  • Regex can be very complex and powerful.
  • Regex is often used to validate user input.

πŸ€” Did You Know?

  • Did you know that regex is used in search engines?
  • Did you know that regex can be used to parse HTML?
  • Did you know that regex is a key skill for data scientists?
  • Did you know that regex can be slow for large text?

🧠 Remember This

  • Regex is for pattern matching.
  • Import re to use regex.
  • Use quantifiers for repetition.
  • Escape special characters.
  • Use search(), findall(), sub(), split().
  • Apply regex in Pandas with str methods.
  • Regex can extract, replace, and validate text.

❌ Common Mistakes

  • Not escaping special characters: Forgetting to escape . or *.
  • Using wrong quantifiers: Using + instead of *.
  • Not using raw strings: Forgetting r before pattern.
  • Overcomplicating: Making patterns too complex.
  • Not testing: Not testing regex on sample text.

βœ… Best Practices

  • Use raw strings for patterns: r'...'.
  • Start with simple patterns and build complexity.
  • Test regex on sample text before applying to full data.
  • Use comments to document complex patterns.
  • Use regex in Pandas for efficient text cleaning.
  • Validate results after cleaning.

πŸ“Š Clear ASCII Illustrations

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
    

πŸ“‹ Comparison Tables

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

πŸ“Œ End-of-Module Summary

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!

❓ Frequently Asked Questions

  1. What is regex? A pattern to match text.
  2. How do you import regex? import re
  3. What is \d? Matches a digit.
  4. What is +? One or more.
  5. What is *? Zero or more.
  6. What is ? Zero or one.
  7. What does re.search() do? Finds first match.
  8. What does re.findall() do? Finds all matches.
  9. What does re.sub() do? Replaces matches.
  10. Can regex be used in Pandas? Yes, with str methods.

πŸ“ Review Questions

  1. What is a regular expression?
  2. How do you import the regex module?
  3. What is the pattern for a digit?
  4. What does + mean in regex?
  5. What does * mean in regex?
  6. What does ? mean in regex?
  7. What does re.search() do?
  8. What does re.findall() do?
  9. What does re.sub() do?
  10. What does re.split() do?
  11. How do you use regex in Pandas?
  12. Give a Nigerian example of using regex.
  13. Give a home example of using regex.
  14. What is the benefit of using regex?
  15. What is a common text cleaning task with regex?

✍️ Fill-in-the-Blank

  1. ______ are patterns to match text. (Regular expressions)
  2. Use ______ to import the regex module. (import re)
  3. ______ matches any digit. (\d)
  4. ______ means one or more. (+)
  5. ______ means zero or more. (*)
  6. ______ means zero or one. (?)
  7. ______ finds the first match. (re.search())
  8. ______ finds all matches. (re.findall())
  9. ______ replaces matches. (re.sub())
  10. ______ splits text by pattern. (re.split())

βœ… True or False

  1. Regex is only for numbers. (False)
  2. re is Python's regex module. (True)
  3. \d matches a letter. (False)
  4. + means zero or more. (False)
  5. * means zero or more. (True)
  6. ? means zero or one. (True)
  7. re.search() finds all matches. (False)
  8. re.findall() finds all matches. (True)
  9. re.sub() replaces matches. (True)
  10. Regex cannot be used in Pandas. (False)

πŸ”˜ Multiple Choice Questions

  1. What is regex?
    A) A type of data
    B) A pattern to match text
    C) A Python library
    D) A file format
    Answer: B
  2. How do you import regex?
    A) import re
    B) import regex
    C) import rex
    D) import regular
    Answer: A
  3. What is \d?
    A) A digit
    B) A letter
    C) A space
    D) A special character
    Answer: A
  4. What does + mean?
    A) Zero or more
    B) One or more
    C) Zero or one
    D) Exactly one
    Answer: B
  5. What does * mean?
    A) Zero or more
    B) One or more
    C) Zero or one
    D) Exactly one
    Answer: A
  6. What does ? mean?
    A) Zero or more
    B) One or more
    C) Zero or one
    D) Exactly one
    Answer: C
  7. What does re.search() do?
    A) Finds first match
    B) Finds all matches
    C) Replaces matches
    D) Splits text
    Answer: A
  8. What does re.findall() do?
    A) Finds first match
    B) Finds all matches
    C) Replaces matches
    D) Splits text
    Answer: B
  9. What does re.sub() do?
    A) Finds first match
    B) Finds all matches
    C) Replaces matches
    D) Splits text
    Answer: C
  10. What does re.split() do?
    A) Finds first match
    B) Finds all matches
    C) Replaces matches
    D) Splits text
    Answer: D
  11. Which method is used in Pandas for regex?
    A) str.contains()
    B) str.extract()
    C) str.replace()
    D) All of the above
    Answer: D
  12. Which is a Nigerian example of regex?
    A) Extracting phone numbers
    B) Extracting movie titles
    C) Extracting video game scores
    D) Extracting sports statistics
    Answer: A
  13. What is a common regex task?
    A) Removing extra spaces
    B) Adding numbers
    C) Creating graphs
    D) Analyzing data
    Answer: A
  14. What is the benefit of regex?
    A) Fast pattern matching
    B) Slow execution
    C) Complex syntax
    D) Limited use
    Answer: A
  15. What is the first step in regex?
    A) Define pattern
    B) Import re
    C) Apply to data
    D) Validate results
    Answer: B

πŸ”— Matching Exercises

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

✏️ Short Answer Questions

  1. What is regex and why is it useful?
  2. What is the difference between re.search() and re.findall()?
  3. How do you replace text using regex?
  4. Give a Nigerian example of using regex.
  5. What is the benefit of using regex in Pandas?

🎭 Scenario-based Exercises

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.

πŸ‘₯ Group Activity

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.

πŸ§‘ Individual Activity

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.

πŸ’¬ Classroom Discussion Questions

  • Why is regex important for data cleaning?
  • What are some challenges in writing regex patterns?
  • How can regex help Nigerian businesses?
  • What are the limitations of regex?
  • How can you practice and improve your regex skills?

πŸ› οΈ Mini Project

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.

πŸ“„ Practical Assignment

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.

πŸ† Challenge Exercise

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.

πŸ” Quiz Answers

Answers to the Multiple Choice Questions are already provided above. For other exercises, refer to the lessons and key vocabulary.

🎁 Key Takeaways

  • Regex is a powerful tool for pattern matching in text.
  • Import re to use regex.
  • Use quantifiers like +, *, ?.
  • Escape special characters with \.
  • Use search(), findall(), sub(), split().
  • Apply regex in Pandas with str methods.
  • Regex can extract, replace, and validate text.

πŸ”œ Preparation for Module Nine

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!

πŸ† Get Certified

πŸ”’

Earn this certificate

Every lesson is already free to read. Sign up, finish the lessons, pass the exam (₦2,000 or 20,000 coins), and get a verified certificate with your name on it.

πŸŽ“ Sign Up to Get Certified
πŸ› οΈ Practice Tools
Hands-on simulators & labs - subscription required.
β†’
🎯 Internship Tasks
Real-world tasks to build your portfolio - unlock them with a subscription.
β†’