跳到正文

第 13 课 · Types, Text and Dates

Cleaning Text with Python and Regex

Clean text data in Python: fix invisible spaces, normalize Unicode and letter case, and use regular expressions to extract and validate structured values.

Text is where people type freely, so it holds a wide variety of errors. Some are visible, such as odd capitals. Others are invisible: a non-breaking space, or two different encodings of the same accented letter. This lesson gives you tools for both.

Whitespace and invisible characters

strip() removes whitespace at both ends. split() with no argument splits on any run of whitespace, so " ".join(text.split()) also collapses repeated spaces. Some invisible characters, such as the zero-width space, do not count as whitespace and need separate handling.

Python Reveal and remove invisible characters

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

repr() is one of your best debugging tools: it helps show what is really in a string. Here the zero-width space stood between two words, so we replaced it with a space. Inside a single word you would remove it instead. Look before you choose.

Unicode normalization

The letter é can be one character, or e followed by a combining accent. They look the same but compare as different. Normalization converts text to one form. NFC composes characters and is a sensible default for storage. NFKC also folds compatibility characters, such as full-width letters, which changes more.

Python Two ways to write the same word

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that NFKC rewrote ½ into separate characters. Use it for matching keys when that is acceptable, and keep the original text.

Letter case

Use casefold() to compare text without regard to case. For display, be careful with title(): it turns "McDonald" into Mcdonald and "they're" into They'Re. Do not "fix" the capitals of personal names automatically. People know how their names are written.

Removing accents: think twice

Stripping accents can help searching, but in many languages it changes meaning. Build a separate search key and leave the stored value alone.

Regular expressions for cleaning

A regular expression describes a text pattern. Four functions cover much of cleaning:

Function Use
re.fullmatch Does the whole value fit the pattern?
re.search Is the pattern somewhere inside?
re.findall Collect all matches
re.sub Replace matches

For validation use fullmatch. With an unanchored search, a value with extra junk around a valid part still passes.

Python Validate, extract and replace

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Named groups such as (?P<number>...) make extraction readable. The phone pattern is only a rough finder. Phone and address formats vary widely between countries, so for serious validation use a maintained library designed for that job.

Splitting combined fields

A column such as "Lima, PE" holds two variables. Split it, but check how many parts each value has. rsplit(",", 1) splits at the last comma, which helps when the first part may contain commas. Count the values that do not split into the expected pieces.

pandas string methods

pandas applies similar operations to whole columns through .str, and missing values stay missing.

Python pandas: clean a text column

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Pass regex=True or regex=False to str.replace so your intent is clear. With False, characters such as . are treated literally.

Keep it testable

Put each text rule in a small function and keep a list of examples, including tricky ones, with the expected output. Run it again whenever you edit a rule.

Common mistake: applying one cleaning function to every text column. Lowercasing and removing punctuation may help a category column and ruin comments, codes or names.

Build a comparison key

It helps to separate two ideas. The stored value is what you show people, cleaned only in safe ways, such as trimming spaces and normalizing Unicode. The comparison key is a more aggressive version that you use only for matching and grouping: casefolded, with punctuation and extra spaces removed, and perhaps without accents if your use allows it. When you keep both columns, you can change the matching rule later without damaging what people typed.

Read patterns carefully

A regular expression can be correct for your examples and wrong for the next file. Test for these traps:

  • A dot matches almost any character unless you escape it.
  • Greedy quantifiers such as .* take as much as they can, which can swallow two fields at once.
  • In Python, \d and \w also match digits and letters from other scripts. Use [0-9] when you mean only those ten digits.
  • Complicated nested repetitions can make matching extremely slow on some inputs.

Long patterns can be written over several lines with the re.VERBOSE flag and comments. If a pattern becomes hard to explain, two or three simple steps are usually easier to maintain.

Free text

Comments, descriptions and notes are different from codes. Do not rewrite them to make them tidy. If you need to analyze them, work on a copy and record each transformation. Free text can also hide personal details that other columns do not have, so check it before you share a file.

Count what each rule changes

After a text rule runs, count the changed values and view a sample of before and after pairs, using repr() so that spaces are visible. Also count the distinct values before and after. If thousands of different names collapse into a few hundred, the rule is far too aggressive.

Order matters

Normalize Unicode and spaces before you apply patterns or lookups. Otherwise an invisible difference can make a correct pattern fail on a value that looks perfectly fine on screen.

Check your understanding

Quick check · 3 questions

of 3 answered You scored / 3 · perfect!

  1. 1. Two strings look identical but compare as unequal. Which step may help?

    The same visible character can be encoded in different ways, and normalization unifies many of them.
  2. 2. Which function checks that an entire value matches a pattern?

    fullmatch requires the pattern to cover the whole string.
  3. 3. Why avoid automatic title case on personal names?

    Capitalization of names varies, and simple title casing gets many wrong.

Summary

  • Use repr() to look for invisible characters.
  • Normalize Unicode and use casefold() for comparisons.
  • Validate with fullmatch and extract with groups.
  • Keep original values and apply rules per column.

Next: Standardizing Categories

你的学习进度保存在此浏览器中,无需账号。