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.

PythonData Integrity

Code

pythonsnippet
28 lines
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 unicodedata as 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

FAQ

Are there third-party dependencies?
`unicodedata` — install it with the package manager before running.