← 中文资源

简体中文版本

unicodedata.category 给字符分类

unicodedata.category 给每个字符类别代号:Lu/Ll 字母、Nd 数字、Po/Pd 标点、Zs 空白、Cc/Cf 控制与格式符;按白名单过滤即可洗掉零宽字符与控制符。

阅读英文原文

实现说明

循环只出现在 for ch in ['R', 'é', '—', '\u00a0', '\u200b', '\u0003'],它的每次迭代处理一个元素。 note、tally、cleaned 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 预留安装步骤:unicodedata 是真实依赖,由包管理器解析。
  • 每一步打印都带着自己的标签:tally:、before:、after:。

常见问题

需要安装第三方包吗?

需要——unicodedata。运行前请先加入项目依赖。

核心语句

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)}')

代码示例

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))