gpt4 book ai didi

python - 完整的 Python 标点符号集(不仅仅是 ASCII)

转载 作者:行者123 更新时间:2023-12-01 07:11:23 24 4
gpt4 key购买 nike

是否有包含我们可能经常遇到的所有标点符号的列表或库?

通常我使用 string.punctuation ,但其中不包含一些标点符号,例如:

>>> "'" in string.punctuation
True
>>> "’" in string.punctuation
False

最佳答案

您可能会通过此检查做得更好:

>>> import unicodedata
>>> unicodedata.category("'").startswith("P")
True
>>> unicodedata.category("’").startswith("P")
True

Unicode 类别 P* 专供 标点符号 :

连接器 (Pc)、破折号 (Pd)、初始报价 (Pi)、最终报价 (Pf)、打开 (Ps)、关闭 (Pe)、其他 (Po)

要准备详尽的集合,您随后可以将其用于快速成员资格检查,请使用集合理解:
>>> import sys
>>> from unicodedata import category
>>> codepoints = range(sys.maxunicode + 1)
>>> punctuation = {c for i in codepoints if category(c := chr(i)).startswith("P")}
>>> "'" in punctuation
True
>>> "’" in punctuation
True

Assignment expression这里需要 Python 3.8+,相当于旧的 Python 版本:
chrs = (chr(i) for i in range(sys.maxunicode + 1))
punctuation = set(c for c in chrs if category(c).startswith("P"))

请注意 string.punctuation 中的一些其他字符实际上属于 Unicode 类别 符号 .如果您愿意,也可以轻松添加这些内容。

关于python - 完整的 Python 标点符号集(不仅仅是 ASCII),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60983836/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com