我该如何做案件
我如何在Python中进行不区分大小写的字符串比较?
我想用一种非常简单的Pythonic方式将常规字符串与存储库字符串进行比较。 我也希望能够使用普通的python字符串来查看由字符串散列的字典中的值。
假设ASCII字符串:
string1 = 'Hello'
string2 = 'hello'
if string1.lower() == string2.lower():
print "The strings are the same (case insensitive)"
else:
print "The strings are not the same (case insensitive)"
以不区分大小写的方式比较字符串看起来很平凡,但事实并非如此。 我将使用Python 3,因为Python 2在这里是欠发达的。
首先要注意的是,在unicode中删除转换的情况并不是微不足道的。 有text.lower() != text.upper().lower()文本,例如"ß" :
"ß".lower()
#>>> 'ß'
"ß".upper().lower()
#>>> 'ss'
但让我们假设你想"Buße"比较"BUSSE"和"Buße" 。 哎呀,你可能还想比较一下"BUSSE"和"BUẞE" - 这是最新的资本形式。 推荐的方法是使用casefold :
help(str.casefold)
#>>> Help on method_descriptor:
#>>>
#>>> casefold(...)
#>>> S.casefold() -> str
#>>>
#>>> Return a version of S suitable for caseless comparisons.
#>>>
不要只使用lower 。 如果casefold不可用,那么执行.upper().lower()帮助(但只是有点)。
那么你应该考虑口音。 如果你的字体渲染器很好,你可能会认为"ê" == "ê" - 但它不会:
"ê" == "ê"
#>>> False
这是因为他们实际上是
import unicodedata
[unicodedata.name(char) for char in "ê"]
#>>> ['LATIN SMALL LETTER E WITH CIRCUMFLEX']
[unicodedata.name(char) for char in "ê"]
#>>> ['LATIN SMALL LETTER E', 'COMBINING CIRCUMFLEX ACCENT']
处理这个问题的最简单方法是unicodedata.normalize 。 您可能想要使用NFKD标准化,但可随时查看文档。 然后一个
unicodedata.normalize("NFKD", "ê") == unicodedata.normalize("NFKD", "ê")
#>>> True
完成后,这里用函数表示:
import unicodedata
def normalize_caseless(text):
return unicodedata.normalize("NFKD", text.casefold())
def caseless_equal(left, right):
return normalize_caseless(left) == normalize_caseless(right)
使用Python 2,对每个字符串或Unicode对象调用.lower() ...
string1.lower() == string2.lower()
......大部分时间都会工作,但在@tchrist所描述的情况下确实不起作用。
假设我们有一个名为unicode.txt的文件, unicode.txt包含两个字符串Σίσυφος和ΣΊΣΥΦΟΣ 。 使用Python 2:
>>> utf8_bytes = open("unicode.txt", 'r').read()
>>> print repr(utf8_bytes)
'xcexa3xcexafxcfx83xcfx85xcfx86xcexbfxcfx82nxcexa3xcex8axcexa3xcexa5xcexa6xcex9fxcexa3n'
>>> u = utf8_bytes.decode('utf8')
>>> print u
Σίσυφος
ΣΊΣΥΦΟΣ
>>> first, second = u.splitlines()
>>> print first.lower()
σίσυφος
>>> print second.lower()
σίσυφοσ
>>> first.lower() == second.lower()
False
>>> first.upper() == second.upper()
True
Σ字符有两个小写形式,ς和σ,而.lower()将无法区分大小写。
但是,从Python 3开始,所有三种形式都将解析为ς,并且在两个字符串上调用lower()都将正确运行:
>>> s = open('unicode.txt', encoding='utf8').read()
>>> print(s)
Σίσυφος
ΣΊΣΥΦΟΣ
>>> first, second = s.splitlines()
>>> print(first.lower())
σίσυφος
>>> print(second.lower())
σίσυφος
>>> first.lower() == second.lower()
True
>>> first.upper() == second.upper()
True
所以如果你关心像希腊三个sigma这样的边缘情况,可以使用Python 3。
(作为参考,Python 2.7.3和Python 3.3.0b1显示在上面的解释器打印输出中。)
链接地址: http://www.djcxy.com/p/58527.html上一篇: How do I do a case
