Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/290.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python语言环境感知字符串比较_Python_String - Fatal编程技术网

Python语言环境感知字符串比较

Python语言环境感知字符串比较,python,string,Python,String,在德语中,eszett字母“ß”相当于“ss” Python允许区域设置感知字符串比较,如下所示: >>> foo = u'strasse' >>> bar = u'stra\xdfe' >>> print(bar.encode('utf-8')) straße >>> import locale >>> locale.setlocale(locale.LC_ALL, 'de_DE') 'de_DE' &g

在德语中,eszett字母“ß”相当于“ss”

Python允许区域设置感知字符串比较,如下所示:

>>> foo = u'strasse'
>>> bar = u'stra\xdfe'
>>> print(bar.encode('utf-8'))
straße
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'de_DE')
'de_DE'
>>> locale.strcoll(foo, bar)
-12
>>> locale.setlocale(locale.LC_ALL, 'de_DE.utf8')
'de_DE.utf8'
>>> locale.strcoll(foo, bar)
-28
我如何比较foo和bar,并知道它们实际上是等价的

(当语言环境设置为德语时,为什么locale.strcoll(foo,bar)不返回0?)

我只是想澄清一下,我对通用解决方案感兴趣,而不是针对德语。Java的语言环境感知字符串比较解决方案是它的类。C的解是它的类。Python有这样的东西吗?(如果不是,是不是应该?)

出于好奇,这里有一个在Java中使用Collator的示例:

import java.text.Collator;
import java.util.Locale;

public class CompareStrings {
    public static void main(String[] args) {
        Collator coll = Collator.getInstance(Locale.GERMAN);
        coll.setStrength(Collator.PRIMARY);
        if (coll.compare("strasse", "straße") == 0) {
            System.out.println("Strings are equivalent");
        } else {
            System.out.println("Strings are not equivalent");
        }
    }
}
输出为“字符串等效”。

使用模块

输出:

strasse

这个从一个脚本到另一个脚本的转换过程被称为。

如果您不需要外部模块,那么这个黑客怎么办:

def isEquivalent(str1, str2):
    return ( locale.strxfrm(str2[:-1]) < locale.strxfrm(str1) <= locale.strxfrm(str2) < locale.strxfrm(str1+"0") 
    or 
    locale.strxfrm(str1[:-1]) < locale.strxfrm(str2) <= locale.strxfrm(str1) < locale.strxfrm(str2+"0") )
def等效(str1、str2):

return(locale.strxfrm(str2[:-1])def isEquivalent(str1, str2): return ( locale.strxfrm(str2[:-1]) < locale.strxfrm(str1) <= locale.strxfrm(str2) < locale.strxfrm(str1+"0") or locale.strxfrm(str1[:-1]) < locale.strxfrm(str2) <= locale.strxfrm(str1) < locale.strxfrm(str2+"0") )