Intermediate level · Module 1: Advanced Text Preprocessing · Lesson 2 of 3
Building a Reusable Preprocessing Module
Learners move cleaning code out of notebooks into a tested Python module, so that every experiment and the final system preprocess text identically.
In this lesson you will
- Package preprocessing functions in a module
- Test preprocessing with small examples
Key concepts
module (.py file)function parameterssimple tests with assertconfigurable stepsconsistency between training and use
The lesson
Copying cleaning code between notebooks leads to small differences that silently change results. Put the functions in a file such as textprep.py and import them: from textprep import clean, tokens.
Make steps configurable with parameters, for example clean(text, mask_numbers=True, keep_negations=True), so that experiments can compare options without editing code.
Test with short examples: assert clean('Call 0912 345 678!!') == 'call <PHONE>!'. Tests catch mistakes when the code changes later and document what each function is supposed to do.
Step by step
- Move clean(), mask() and tokens() into textprep.py.
- Add parameters for the main options.
- Write five assert tests and run them.
- Import the module in two notebooks and confirm identical outputs.
Practice activity
Create and test the level project's preprocessing module.
Expected result: A module with documented, tested functions that all project notebooks use.
Check your understanding
-
Why move preprocessing into a module?
Show answer
So that every notebook and the final system clean text in exactly the same way.
-
What does a test like assert clean(x) == y check?
Show answer
That the function produces the expected output for a known input.
Further learning
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.