1) 在 Python 3 中,casefold() 应该用于实现无大小写字符串匹配。
从 Python 3.0 开始,字符串存储为 Unicode。 The Unicode Standard Chapter 3.13 定义默认无大小写匹配如下:
字符串 X 是字符串 Y 的无大小写匹配当且仅当:
toCasefold(X) = toCasefold(Y)
Python's casefold() implements the Unicode's toCasefold(). 所以,应该用它来实现无大小写的字符串匹配。虽然,仅靠外壳折叠不足以覆盖一些极端案例并通过土耳其测试(参见第 3 点)。
2) 从 Python 3.6 开始,casefold() 无法通过土耳其测试。
对于两个字符,大写 I 和点大写 I,the Unicode Standard defines two different casefolding mappings.
默认(非突厥语):
我 → 我 (U+0049 → U+0069)
İ → i̇ (U+0130 → U+0069 U+0307)
替代方案(用于突厥语):
我 → ı (U+0049 → U+0131)
© → i (U+0130 → U+0069)
Pythons casefold() 只能应用默认映射并且无法通过土耳其测试。例如,土耳其语单词“LİMANI”和“limanı”是无大小写的等价词,但"LİMANI".casefold() == "limanı".casefold() 返回False。没有启用替代映射的选项。
3) 如何在 Python 3 中进行无大小写字符串匹配。
The Unicode Standard Chapter 3.13 描述了几种无条件匹配算法。 canonical casless matching 可能适合大多数用例。该算法已经考虑了所有极端情况。我们只需要添加一个选项就可以在非突厥语和突厥语折叠之间切换。
import unicodedata
def normalize_NFD(string):
return unicodedata.normalize('NFD', string)
def casefold_(string, include_special_i=False):
if include_special_i:
string = unicodedata.normalize('NFC', string)
string = string.replace('\u0049', '\u0131')
string = string.replace('\u0130', '\u0069')
return string.casefold()
def casefold_NFD(string, include_special_i=False):
return normalize_NFD(casefold_(normalize_NFD(string), include_special_i))
def caseless_match(string1, string2, include_special_i=False):
return casefold_NFD(string1, include_special_i) == casefold_NFD(string2, include_special_i)
casefold_() 是 Python 的 casefold() 的包装器。如果其参数include_special_i 设置为True,则应用Turkic 映射,如果设置为False,则使用默认映射。
caseless_match() 对string1 和string2 进行规范的无大小写匹配。如果字符串是突厥语单词,include_special_i参数必须设置为True。
示例:
>>> caseless_match('LİMANI', 'limanı', include_special_i=True)
True
>>> caseless_match('LİMANI', 'limanı')
False
>>> caseless_match('INTENSIVE', 'intensive', include_special_i=True)
False
>>> caseless_match('INTENSIVE', 'intensive')
True