Sub topic 6
Removing Accents and Diacritics Safely
What accent stripping does
A diacritic is a mark added to a letter, such as the acute accent in é, the diaeresis in ï, or the tilde in ñ. Accent stripping removes these marks so that text such as café becomes cafe.
This can help when a search should match users who omit accents. For example, a query for cafe might reasonably find café. However, the operation can also remove meaningful information. In Spanish, ñ is a distinct letter, not simply an accented n. In Vietnamese, many diacritics affect pronunciation and meaning.
Assume you know basic Python strings, loops, functions, and list comprehensions. You should also understand that Unicode represents text with code points and that one visible character can contain several code points.
Decompose, filter, and recompose
Unicode normalization form D, or NFD, decomposes a character into a base character and its combining marks. For example, é can become:
e, the base character- a combining acute accent
Python's unicodedata.combining() function identifies combining marks. A value of zero means that the character is not a combining mark.
After filtering the marks, normalize the result back to NFC. This recomposes any remaining sequences into their usual canonical form.
import unicodedata
def strip_accents(text):
decomposed = unicodedata.normalize("NFD", text)
kept = "".join(
character
for character in decomposed
if not unicodedata.combining(character)
)
return unicodedata.normalize("NFC", kept)
print(strip_accents("café naïve")) # cafe naiveThe function does not replace characters using a manually written table. It works with Unicode's decomposition data, so it handles many scripts and characters consistently.
NFD versus NFKD
NFD performs canonical decomposition. It separates characters that have a standard equivalent representation, such as é into e plus an acute accent.
NFKD performs compatibility decomposition. It also expands characters that are visually or functionally related to simpler characters. For example, a ligature such as fi becomes f and i, and some full-width characters become ordinary-width characters.
| Form | Main purpose | Example effect |
|---|---|---|
| NFD | Separate canonical base characters and marks | `é` becomes `e` plus an acute accent |
| NFKD | Also expand compatibility characters | `fi` becomes `fi` |
Use NFD when your specific goal is to remove combining accents. Use NFKD only when compatibility differences should also disappear. NFKD can remove distinctions that matter to your application.
import unicodedata
text = "fiancée"
print(unicodedata.normalize("NFD", text))
# fiancée
print(unicodedata.normalize("NFKD", text))
# fiancéeIn the NFD result, the fi ligature remains. In the NFKD result, it expands to fi.
Selective removal is safer
Removing every combining mark is a broad rule. It can change letters that users and languages treat as separate characters. For example, this function changes mañana to manana, which may be undesirable for Spanish text.
A safer design can apply accent stripping only in a search key while preserving the original text for display, storage, and language analysis.
import unicodedata
def search_key(text):
decomposed = unicodedata.normalize("NFD", text)
without_marks = "".join(
character
for character in decomposed
if not unicodedata.combining(character)
)
return unicodedata.normalize("NFC", without_marks).casefold()
original = "Mañana en el Café"
print(original) # Mañana en el Café
print(search_key(original)) # manana en el cafeThe original value remains available. Only the comparison key loses the marks.
You can also preserve selected marks by checking the character's Unicode name or by applying language-specific rules. Those rules require knowledge of the text's language. A universal accent-stripping function cannot decide whether every mark is decorative, optional, or meaningful.
Where it belongs in a pipeline
Normalize Unicode before removing combining marks. If you strip marks first, equivalent representations may behave differently. Apply case folding after the text has reached the form expected by the rest of the pipeline. Tokenization can follow the normalization steps.
Decide based on the task
Accent stripping can improve recall in search, where finding more possible matches is useful. It may harm precision if different names or words become identical. It is usually risky for named entity recognition, language identification, spelling correction, and sentiment analysis because the marks may carry linguistic information.
Test the transformation with representative data from every language you support. Check collisions, where two different inputs produce the same output. Store the original text, the normalization policy, and the generated key so that results can be explained and rebuilt later.
Exercise
Why does the example use NFD before filtering and NFC afterward, and when might you avoid stripping accents?
Show answer
NFD exposes combining marks so they can be filtered. NFC recomposes the remaining text into a canonical form. Avoid stripping accents when the marks distinguish words, names, or other information needed by the task.