81. Filter Low-Quality Training Text
Difficulty: Medium · Topics: Data Prep for AI, Strings, Null Handling
Before pre-training, a corpus pages (page_id, text) is filtered with simple quality rules. Drop a page when any of these is true:
textis null, or shorter than 20 characters.- More than 30% of its characters are neither letters (A–Z, a–z) nor spaces: menus, tables of numbers and code dumps.
- It contains the same character 5 or more times in a row (
!!!!!,aaaaa): spam.
Return the page_id, text of the pages that are kept.
Row order does not matter; column names must match. Your code is graded on 3 test cases, including hidden edge cases.
Sample data
pages
| page_id | text |
|---|---|
| 1 | Spark runs jobs on a cluster of machines |
| 2 | Too short |
| 3 | Home | About | 2024 | 99 | 12 | 34 | 56 |
| 4 | Buy now!!!!! Limited offer for everyone |
Expected output
| page_id | text |
|---|---|
| 1 | Spark runs jobs on a cluster of machines |
Hints
Hint 1
The share of other characters: remove letters and spaces withregexp_replace(text, "[A-Za-z ]", "") and compare its length with the length of the whole text.Hint 2
A character repeated 5 or more times is a backreference:(.)\1{4,} with rlike.Hint 3
A null text makes every condition null, andfilter drops rows where the condition is null. Say what you mean anyway: check isNotNull() first.Learn the concepts
- regexp_extract · 8 min read. Extract, filter, replace and collect with a regular expression, and what you get when nothing matches.
- select · 6 min read. Choose, rename and compute columns, and why select beats a chain of withColumn calls.
- filter / where · 5 min read. Keep the rows that match a condition, and the null and operator traps that silently drop data.
PySpark functions you'll practise
- isNotNull
- filter
- select
- regexp_replace
Related problems
- Remove Near-Duplicate Documents · Medium · Data Prep for AI, Window Functions, Strings
- Split Train and Test With No User in Both · Medium · Data Prep for AI, Joins, Aggregations
- Build Preference Pairs from Ratings · Hard · Data Prep for AI, Window Functions, Joins
- Mask Personal Data Before Training · Easy · Data Prep for AI, Strings, Filtering & Selection
- Fit Conversations into a Context Window · Hard · Data Prep for AI, Window Functions, Joins
Browse
Topics: Window Functions · Joins · Aggregations · Pivot, Unpivot & Rollup · Arrays · Null Handling · Conditional Logic · Dates · Filtering & Selection · Strings · Data Lake · Lakehouse · Streaming · Data Prep for AI · Spark Performance
Difficulty: Easy · Medium · Hard · Learn · All problems · dbt practice