您可以使用正则表达式模块 https://pypi.org/project/regex/支持 POSIX 字符类:
import regex
>>> regex.findall('[[:lower:]]', 'u∏ñKθ')
['u', 'ñ', 'θ']
或者,使用Unicode 类别 类 https://www.regular-expressions.info/unicode.html of \p{Ll}
or \p{Lowercase_Letter}
:
>>> regex.findall(r'\p{Ll}', 'u∏ñKθ')
['u', 'ñ', 'θ']
或者只使用 Python 的字符串逻辑:
>>> [c for c in 'u∏ñKθ' if c.islower()]
['u', 'ñ', 'θ']
无论哪种情况,都要小心这样的字符串:
>>> s2='\u0061\u0300\u00E0'
>>> s2
'àà'
首先grapheme https://unicode.org/glossary/#grapheme 'à'
是一个结果'a'
具有组合特征'̀'
第二个在哪里'à'
是该特定代码点的结果。如果您在这里使用字符类,它将匹配'a'
而不是组合重音:
>>> regex.findall('[[:lower:]]', s2)
['a', 'à']
>>> [c for c in s2 if c.islower()]
['a', 'à']
为了解决这个问题,您需要用更复杂的正则表达式模式来解决这个问题,或者规范化字符串 https://stackoverflow.com/questions/16467479/normalizing-unicode:
>>> regex.findall('[[:lower:]]', unicodedata.normalize('NFC',s2))
['à', 'à']
或按字素循环:
>>> [c for c in regex.findall(r'\X', s2) if c.islower()]
['à', 'à']