unicodedata.category Classifies Characters
unicodedata.category assigns every character a class code, so sanitizers can whitelist letters and punctuation while dropping control and format characters.
Code
import collections
import unicodedata
note = 'Café résumé — naïve co‑op\u200b!'
# unicodedata.category 给每个字符一个类别代号:字母、标点、空白、控制符各有归属
for ch in ['R', 'é', '—', '\u00a0', '\u200b', '\u0003']:
print(f'{ch!r:>10} -> {unicodedata.category(ch)}')
# 逐类统计:看一段文本里都混进了什么
tally = collections.Counter(unicodedata.category(ch) for ch in note)
print('tally:', dict(tally))
# 清洗:保留字母/数字/常规标点/普通空格,丢弃控制与格式字符
KEEP = {'Lu', 'Ll', 'Nd', 'Zs', 'Po', 'Pd'}
cleaned = ''.join(ch for ch in note if unicodedata.category(ch) in KEEP)
print('before:', repr(note))
print('after: ', repr(cleaned))unicodedata.category Classifies Characters: reading the source
Iteration happens inside for ch in ['R', 'é', '—', '\u00a0', '\u200b', '\u0003'] — everything outside it runs once.
The file’s state is a handful of top-level bindings: note, tally, cleaned.
Watch out for
- Requires
unicodedataas a package; the snippet will not run without it.
Applying it
The demo output is labeled (tally:, before:, after:), which keeps line-to-operation attribution explicit.
Statements that matter
tally = collections.Counter(unicodedata.category(ch) for ch in note)
print('tally:', dict(tally))
# 清洗:保留字母/数字/常规标点/普通空格,丢弃控制与格式字符
KEEP = {'Lu', 'Ll', 'Nd', 'Zs', 'Po', 'Pd'}
for ch in ['R', 'é', '—', '\u00a0', '\u200b', '\u0003']:
print(f'{ch!r:>10} -> {unicodedata.category(ch)}')
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- Does this require external packages?
- Yes — `unicodedata`. Add it to your project before running the snippet.
Report a problem with this exampleOpens a pre-filled issue on GitHub.