sam*_*249 41 python string unicode
是否有包含我们可能经常遇到的所有标点符号的列表或库?
通常我使用string.punctuation,但其中不包含一些标点符号,例如:
>>> "'" in string.punctuation
True
>>> "’" in string.punctuation
False
Run Code Online (Sandbox Code Playgroud)
wim*_*wim 57
您可能会通过此检查做得更好:
>>> import unicodedata
>>> unicodedata.category("'").startswith("P")
True
>>> unicodedata.category("’").startswith("P")
True
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
此处的赋值表达式需要 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"))
Run Code Online (Sandbox Code Playgroud)
请注意,其中的一些其他字符string.punctuation实际上属于 Unicode 类别Symbol。如果您愿意,也可以轻松添加这些内容。
Sel*_*cuk 18
如果要检查字符是否为标点符号,wim 发布的答案是正确的。
如果您真的需要问题标题所暗示的所有标点符号的列表,您可以使用以下内容:
import sys
from unicodedata import category
punctuation_chars = [chr(i) for i in range(sys.maxunicode)
if category(chr(i)).startswith("P")]
Run Code Online (Sandbox Code Playgroud)