str.translate Maps Codepoints In One Pass
Build a codepoint translation table for smart quotes and dashes, compose with NFC normalization first, and delete whole character classes on the fly.
Code
import unicodedata
# str.translate 的映射表:键是码点序号,值是替换字符串
SANITIZE = {
ord('’'): "'",
ord('“'): '"',
ord('”'): '"',
ord('–'): '-',
ord('—'): '-',
ord(' '): ' ',
}
def normalize_text(raw: str) -> str:
# NFC 先合成等价序列,智能引号/窄空格/长破折号再按表翻译
composed = unicodedata.normalize('NFC', raw)
return composed.translate(SANITIZE)
raw = '“café” – naïve—rung'
print('raw :', ascii(raw))
clean = normalize_text(raw)
print('clean :', ascii(clean))
# 映射表之外的字符原样保留:é、ï 不受影响
print('kept :', 'é' in clean and 'ï' in clean)
# delete 参数一键删字符:辅音骨架
vowels_deleted = 'queueing'.translate(str.maketrans('', '', 'aeiou'))
print('no-vowel:', vowels_deleted)How the snippet works
str.translate Maps Codepoints In One Pass keeps everything in the function normalize_text.
Watch out for
- Requires
unicodedataas a package; the snippet will not run without it.
Applying it
The main signature reads def normalize_text(raw: str) -> str
The demo output is labeled (raw :, clean :, kept :), so every printed line maps back to its originating operation.
Import normalize_text from the file and call it — the rest of the code is implementation detail.
Statements that matter
def normalize_text(raw: str) -> str:
# NFC 先合成等价序列,智能引号/窄空格/长破折号再按表翻译
composed = unicodedata.normalize('NFC', raw)
return composed.translate(SANITIZE)
Interactive Tools for This Topic
ASCII Table ReferenceLook up any ASCII code point 0-127 by decimal, hex, or character and see the binary, octal, and control-name view.Character Frequency AnalyzerCount how often each character appears in a text, with Unicode code points, optional case folding, and whitespace exclusion.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.Text ReverserReverse text by characters, words, or lines, counting Unicode code points so emoji stay intact.
FAQ
- Are there third-party dependencies?
- `unicodedata` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.