@Weetu's answer是Python string predicates对应于Unicode general category properties的一个很好的概述。
作为一个练习,我试图编写一个程序来找出我自己,哪个字符串谓词(例如isdigit
)对应于哪些字符属性。于是我打开了Unicode Character Categories并填充了一个字典,其中键为2个字母的类别('Lt'
),值为示例Unicode字符(u'Dž'
),然后编写了一个程序来获得字符串谓词和字符属性之间的对应关系。我使用了Python 3,因为Python 2有一些神秘的Unicode错误(如果你指出,为什么下面的代码在Python 2中工作不正确,我会很高兴的)。
d = {
'Cc': u'', 'LC': None, 'Pc': u'_', 'Sc': u'$',
'Cf': u'', 'Ll': u'a', 'Pd': u'-', 'Sk': u'^',
'Cn': None, 'Lm': u'ʰ', 'Pe': u')', 'Sm': u'+',
'Co': u'', 'Lo': u'ª', 'Pf': u'»', 'So': u'¦',
'Cs': u'⠀', 'Lt': u'Dž', 'Pi': u'«',
'Lu': u'A', 'Po': u'!',
'Ps': u'(',
'Mc': u'ः', 'Nd': u'0', 'Zl': u'
',
'Me': u'҈', 'Nl': u'ᛮ', 'Zp': u'
',
'Mn': u'̀', 'No': u'²', 'Zs': u' '
} # Zl and Zp have invisible characters that break Markdown's code blocks
methods = ['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle', 'isupper', 'isnumeric', 'isdecimal']
dl = {method: [code
for code, character
in d.items()
if character and getattr(character, method)()]
for method in methods}
结果如下。例如。 ch.isdigit()
将返回True
如果ch
有No
或Nd
Unicode属性。
>>> from pprint import pprint # pretty printing
>>> pprint(dl)
{'isalnum': ['No', 'Nd', 'Nl', 'Lu', 'Lt', 'Lo', 'Lm', 'Ll'],
'isalpha': ['Lu', 'Lt', 'Lo', 'Lm', 'Ll'],
'isdecimal': ['Nd'],
'isdigit': ['No', 'Nd'],
'islower': ['Lo', 'Lm', 'Ll'],
'isnumeric': ['No', 'Nd', 'Nl'],
'isspace': ['Zp', 'Zs', 'Zl'],
'istitle': ['Lu', 'Lt'],
'isupper': ['Lu']}
对于使用Unicode字符数据库的更智能操作,请参阅Python库unicodedata。
参考文献:
感谢这个不错的概述!这将有很大的帮助。 – LarsVegas 2012-02-28 12:03:26