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.

PythonSecurity Boundaries

Code

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

FAQ

Does this require external packages?
Yes — `unicodedata`. Add it to your project before running the snippet.