【问题标题】:Should I use Python casefold?我应该使用 Python casefold 吗?
【发布时间】:2020-12-17 02:20:35
【问题描述】:

最近阅读了忽略大小写时的大小写和字符串比较。我读过 MSDN 标准是使用 InvariantCulture 并且绝对避免使用 toLowercase。但是,从我读过的内容来看,casefold 就像一个更具侵略性的 toLowercase。我的问题是我应该在 Python 中使用 casefold 还是有更多的 Pythonic 标准可以代替?另外,casefold 是否通过了土耳其测试?

【问题讨论】:

  • 1. casefold 做了什么解释 in the docs。 2. 在这种情况下,“更好”是什么意思? 3. 什么是土耳其语测试(您是否尝试过运行它来找出答案)?
  • @jonrsharpe 抱歉,这意味着更多的pythonic,也意味着土耳其测试。我只是想知道优秀的程序员在 python 中进行无大小写比较时使用什么。
  • @jonrsharpe - 土耳其语测试在这里有更详细的描述stackoverflow.com/a/797043/135978
  • 你试过casefold自己看看它是否通过了土耳其测试吗?
  • @jonrsharpe 老实说,我还没有时间尝试它。我还没有遇到需要使用 casefold 的情况。这只是我做了一些闲散的研究后想到的一个问题。如果我确实要测试它,我一定会发布我的结果。最后,我最大的问题仍然是:casefold 是最 Pythonic 的忽略大小写的方式吗?

标签: python python-3.x case-folding


【解决方案1】:

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

【讨论】:

  • 干得好。 casefold_ 函数不需要以 _ 结尾,因为它不会隐藏内置函数或关键字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-12-26
  • 2021-12-10
  • 2010-12-25
  • 2014-05-27
  • 2010-12-25
  • 2018-09-11
相关资源
最近更新 更多