Text processing · 4 / 14 Theory

Cleaning and normalizing text

The texts that people write arrive messy: mixed capitals, extra spaces, accents, signs. Normalizing is transforming them into a standard form so they can be compared, counted or validated.

Upper and lower case

text = "hELLo wORLD"

print(text.lower())        # hello world
print(text.upper())        # HELLO WORLD
print(text.capitalize())   # Hello world   (only the first letter of the text)
print(text.title())        # Hello World   (each word)
print(text.swapcase())     # HellO WorlD

To compare without distinguishing case you have to convert both texts to lower case (or use casefold(), which also handles cases such as the German ß):

print("Hello" == "hello")                  # False
print("Hello".lower() == "hello".lower())  # True

title() has a known flaw with apostrophes: "o'neil".title() gives O'Neil, but "it's".title() gives It'S. For names, it is safer to apply capitalize() to each word:

name = "ana    MARIA  garcia"

words = []
for w in name.split():
    words.append(w.capitalize())

print(" ".join(words))   # Ana Maria Garcia

Extra spaces

The combination " ".join(text.split()) removes the spaces at the beginning and the end and leaves a single space between words:

dirty = "   hello     world   "
print(" ".join(dirty.split()))   # hello world

Keeping only letters and numbers

sentence = "¡Hello, World! 123"

clean = ""
for c in sentence:
    if c.isalnum():
        clean += c

print(clean)   # HelloWorld123

translate: replacing or removing many characters

str.maketrans builds a conversion table that translate applies in a single pass. With three arguments, the third one is the characters to remove:

table = str.maketrans("áéíóú", "aeiou")
print("canción rápida".translate(table))   # cancion rapida

no_signs = str.maketrans("", "", ".,;:!?")
print("hello, world!".translate(no_signs))  # hello world

Removing accents with unicodedata

To remove the accents of any letter, each character is decomposed into its base letter plus its accent (NFD) and the accents are discarded:

import unicodedata

def remove_accents(text):
    decomposed = unicodedata.normalize("NFD", text)
    result = ""
    for c in decomposed:
        if unicodedata.category(c) != "Mn":   # Mn = accent mark
            result += c
    return result

print(remove_accents("Canción, niño y pingüino"))   # Cancion, nino y pinguino

A complete example: palindromes

A sentence is a palindrome if it reads the same forwards and backwards, ignoring capitals, spaces and signs. Normalizing first simplifies everything:

def is_palindrome(sentence):
    clean = ""
    for c in sentence.lower():
        if c.isalnum():
            clean += c
    return clean == clean[::-1]

print(is_palindrome("Anita lava la tina"))             # True
print(is_palindrome("A man, a plan, a canal: Panama")) # True
print(is_palindrome("Hello"))                          # False

Practice in Normalize names and Palindromes.