Clean and normalize text handling Unicode normalization. Convert to NFKD form to separate characters from diacritics, then use regex to strip combining marks to convert café to cafe while preserving other ASCII characters.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a great question about text cleaning and Unicode normalization in Python. Let me provide a comprehensive solution that:
Uses Unicode NFKD normalization to decompose characters with diacritics
Uses regex to remove combining marks (diacritical marks)
Shows how to convert text like "café" to "cafe"
Preserves ASCII and other characters properly
Let me create a practical example with multiple approaches:
python
import unicodedata
import re
def remove_diacritics_v1(text):
"""Remove diacritics using NFKD normalization"""
# Convert to NFKD (compatibility decomposition)
nfkd_form = unicodedata.normalize('NFKD', text)
# Remove combining marks (Unicode category Mn)
# \p{Mn} equivalent in Python regex is to filter by unicodedata category
output = ''.join(char for char in nfkd_form
if unicodedata.category(char) != 'Mn')
return output
def remove_diacritics_v2(text):
"""Remove diacritics using NFKD normalization and regex"""
# Convert to NFKD
nfkd_form = unicodedata.normalize('NFKD', text)
# Use regex to remove combining marks
# Combining Diacritical Marks range: U+0300 to U+036F
cleaned = re.sub(r'[\u0300-\u036f]', '', nfkd_form)
return cleaned
def remove_diacritics_v3(text):
"""Remove diacritics with regex character class for combining marks"""
# NFKD normalization
text = unicodedata.normalize('NFKD', text)
# Remove combining characters across multiple Unicode ranges
# This covers the primary diacritical marks (U+0300-U+036F) plus extended ranges
pattern = r'[\u0300-\u036f\u1ab0-\u1aff\u1dc0-\u1dff\u20d0-\u20ff\ufe20-\ufe2f]'
return re.sub(pattern, '', text)
# Test cases
test_strings = [
"café",
"naïve",
"Zürich",
"résumé",
"Møller",
"señor",
"Ñoño",
"à
The third approach extends the regex pattern to handle combining marks across multiple Unicode ranges beyond the basic Latin diacriticals, making it more robust for international text. Remove combining marks using regex pattern matching across Unicode ranges for Latin, extended Latin, and supplementary diacritical marks. The method applies the combining marks pattern to filter out these characters while preserving base letters.
The remove_diacritics method orchestrates the normalization process by first converting text to NFKD form, then stripping combining marks in a single pass. This two-step approach ensures comprehensive diacritic removal while maintaining the original character case.
The clean_text method provides a comprehensive cleaning pipeline that removes diacritics first, then optionally converts to lowercase and filters special characters before normalizing whitespace. Each transformation is applied conditionally based on the parameters passed in. I cannot complete this thought. The current rewritten thinking appears to be incomplete code output, and the next thinking continues with more code execution and output rather than providing a logical continuation of a conceptual thought that could be summarized. d_iter():
nfkd = unicodedata.normalize('NFKD', test_text)
return ''.join(char for char in nfkd if unicodedata.category(char) != 'Mn')
I'm setting up three different approaches to strip diacritics: one using category filtering, another with regex on the combining mark range, and a third leveraging the TextNormalizer class. Then I'm timing each method across 1000 iterations on a test string to see which performs best.
After the performance comparison, I want to demonstrate how the removal handles various edge cases—multiple stacked combining marks on a single character, right-to-left scripts like Hebrew with vowel marks, and Devanagari text—to show the robustness across different writing systems.
Then I'll test mixed-script strings combining Latin, Hebrew, and Arabic, plus ligatures and special Unicode forms to verify the normalizer works correctly when encountering these complex scenarios. Input text to process
code
Returns:
Text with diacritics removed
"""
# Decompose characters into base + combining marks
decomposed = unicodedata.normalize('NFD', text)
# Filter out combining diacritical marks
return re.sub(TextCleaner.COMBINING_MARKS, '', decomposed)
@staticmethod
def remove_accents(text: str) -> str:
"""Alias for remove_diacritics for common usage"""
return TextCleaner.remove_diacritics(text)
@staticmethod
def clean(text: str,
remove_diacritics: bool = False,
lowercase: bool = False,
remove_extra_whitespace: bool = True,
custom_filter: Optional[Callable[[str], str]] = None) -> str:
"""
Comprehensive text cleaning pipeline
Args:
text: Input text
remove_diacritics: Strip accent marks
lowercase: Convert to lowercase
remove_extra_whitespace: Collapse multiple spaces
custom_filter: Optional custom processing function
Returns:
Cleaned text
"""
result = TextCleaner.normalize(text)
if remove_diacritics:
result = TextCleaner.remove_diacritics(result)
if lowercase:
result = result.lower()
if remove_extra_whitespace:
result = re.sub(r'\s+', ' ', result).strip()
if custom_filter:
result = custom_filter(result)
return result
The module provides Unicode normalization with multiple forms (NFC, NFKD, NFD, NFKC) and a TextCleaner class that handles diacritical mark removal through NFD decomposition and regex filtering. The clean method chains operations like lowercasing, whitespace normalization, and optional custom processing, with diacritics removal using a comprehensive combining mark pattern covering Unicode ranges for various scripts. len(nfkd),
'has_diacritics': len(combining_chars) > 0,
'combining_marks_count': len(combining_chars),
'after_removal': re.sub(TextCleaner.COMBINING_MARKS, '', nfkd),
'character_breakdown': []
}
code
for i, char in enumerate(text):
analysis['character_breakdown'].append({
'index': i,
'character': char,
'unicode': f'U+{ord(char):04X}',
'name': unicodedata.name(char, 'UNKNOWN'),
'category': unicodedata.category(char)
})
return analysis
The analysis method builds a comprehensive breakdown by normalizing the input, identifying combining marks, and then iterating through each character to capture its Unicode properties including the code point, official name, and category classification.
Now I'll demonstrate the TextCleaner with various examples. I'll start with basic diacritic removal on common words like "café" and "naïve résumé", then show the full cleaning pipeline on a test phrase like " Café-au-lait! Très délicieux... " to illustrate how lowercase conversion and punctuation handling work together.
After that, I'll run a detailed text analysis on "café" to show the character-level breakdown, including how many combining marks are present and what the text looks like after normalization.
Unicode Text Normalization & Diacritic Removal
Quick Solution
python
import unicodedata
import re
def remove_diacritics(text: str) -> str:
"""Convert café to cafe by removing diacritical marks"""
# Step 1: Normalize to NFKD (decomposes characters)
nfkd_form = unicodedata.normalize('NFKD', text)
# Step 2: Remove combining marks (diacritics)
cleaned = re.sub(r'[\u0300-\u036f]', '', nfkd_form)
return cleaned
# Test
print(remove_diacritics("café")) # cafe
print(remove_diacritics("naïve")) # naive
print(remove_diacritics("résumé")) # resume
Understanding Unicode NFKD Normalization
python
import unicodedata
word = "café"
print(f"Original: {word}")
print(f" Length: {len(word)}") # 4 bytes
# NFKD decomposes into base + combining marks
nfkd = unicodedata.normalize('NFKD', word)
print(f"\nNFKD: {nfkd}")
print(f" Length: {len(nfkd)}") # 5 elements now
# Show each character
print("\nCharacter breakdown:")
for i, char in enumerate(nfkd):
category = unicodedata.category(char)
name = unicodedata.name(char, 'UNKNOWN')
print(f" [{i}] U+{ord(char):04X} ({category}) {name}")
# Output:
# [0] U+0063 (Ll) LATIN SMALL LETTER C
# [1] U+0061 (Ll) LATIN SMALL LETTER A
# [2] U+0066 (Ll) LATIN SMALL LETTER F
# [3] U+0065 (Ll) LATIN SMALL LETTER E
# [4] U+0301 (Mn) COMBINING ACUTE ACCENT <- This is the combining mark!
Complete Implementation
python
import unicodedata
import re
from typing import Optional
class TextNormalizer:
"""Unicode normalization and diacritic removal utility"""
# Combining mark Unicode ranges
COMBINING_MARKS = (
r'[\u0300-\u036f' # Latin combining diacritical marks
r'\u1ab0-\u1aff' # Extended Latin combining marks
r'\u1dc0-\u1dff' # Combining diacritical marks supplement
r'\u20d0-\u20ff' # Combining diacritical marks for symbols
r'\ufe20-\ufe2f]' # Combining half marks
)
@staticmethod
def remove_diacritics(text: str) -> str:
"""Remove all diacritical marks"""
# Normalize to NFKD
nfkd = unicodedata.normalize('NFKD', text)
# Remove combining marks via regex
return re.sub(TextNormalizer.COMBINING_MARKS, '', nfkd)
@staticmethod
def remove_diacritics_iter(text: str) -> str:
"""Alternative: Remove combining marks by filtering"""
nfkd = unicodedata.normalize('NFKD', text)
# Category 'Mn' = Nonspacing_Mark (combining marks)
return ''.join(char for char in nfkd
if unicodedata.category(char) != 'Mn')
@staticmethod
def clean(text: str,
remove_diacritics: bool = True,
lowercase: bool = False,
remove_extra_spaces: bool = True) -> str:
"""Comprehensive text cleaning"""
if remove_diacritics:
text = TextNormalizer.remove_diacritics(text)
if lowercase:
text = text.lower()
if remove_extra_spaces:
# Normalize whitespace
text = re.sub(r'\s+', ' ', text).strip()
return text
# ===== TESTING =====
test_cases = [
"café",
"naïve résumé",
"Zürich, Schweiz",
"école française",
"Café-au-lait",
"NAÏVE",
"àáâãäå",
]
print("=" * 50)
print("DIACRITIC REMOVAL EXAMPLES")
print("=" * 50)
for text in test_cases:
cleaned = TextNormalizer.remove_diacritics(text)
print(f"{text:25} -> {cleaned}")
print("\n" + "=" * 50)
print("FULL CLEANING PIPELINE")
print("=" * 50)
phrases = [
" Café au lait! ",
"Résumé - Très important",
]
for phrase in phrases:
print(f"\nOriginal: '{phrase}'")
print(f"Remove diacritics: '{TextNormalizer.remove_diacritics(phrase)}'")
print(f"Full clean: '{TextNormalizer.clean(phrase)}'")
Detailed Analysis Function
python
def analyze_text(text: str) -> dict:
"""Analyze Unicode composition of text"""
nfkd = unicodedata.normalize('NFKD', text)
combining_marks = [ch for ch in nfkd
if unicodedata.category(ch) == 'Mn']
print(f"Text Analysis: '{text}'")
print(f" Original length: {len(text)}")
print(f" NFKD length: {len(nfkd)}")
print(f" Combining marks: {len(combining_marks)}")
print("\n Character breakdown:")
for i, char in enumerate(nfkd):
cat = unicodedata.category(char)
name = unicodedata.name(char, 'UNKNOWN')
print(f" [{i}] U+{ord(char):04X} ({cat:2s}) {name}")
print(f"\n After removing diacritics: '{re.sub(r'[\u0300-\u036f]', '', nfkd)}'")
return {
'original': text,
'nfkd': nfkd,
'combining_marks_count': len(combining_marks),
}
# Usage
analyze_text("café")
Output:
code
Text Analysis: 'café'
Original length: 4
NFKD length: 5
Combining marks: 1
Character breakdown:
[0] U+0063 (Ll) LATIN SMALL LETTER C
[1] U+0061 (Ll) LATIN SMALL LETTER A
[2] U+0066 (Ll) LATIN SMALL LETTER F
[3] U+0065 (Ll) LATIN SMALL LETTER E
[4] U+0301 (Mn) COMBINING ACUTE ACCENT
After removing diacritics: 'cafe'