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

标签 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'
>>> 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 的区域感知字符串比较解决方案是它的 java.text.Collator类(class)。 C# 的解决方案是它的 System.Globalization.CultureInfo类(class)。 Python有这样的东西吗? (如果不是,不应该吗?)

出于好奇,这里有一个在 Java 中使用 Collat​​or 的例子:

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");
        }
    }
}

输出是“字符串是等价的”。

最佳答案

使用 unidecode模块。

from unidecode import unidecode
print unidecode(u'stra\xdfe')

输出:

strasse

从一个脚本到另一个脚本的转换过程称为 transliteration .

关于Python 语言环境感知字符串比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19830643/

相关文章:

python - 运行 'filename' 时出错。系统找不到指定的文件(PyCharm)

java - 在运行时使用 Class.forName 加载 Weka 类

c# - 在 for 循环语句中动态创建属性名称

java - 将字符串数组与变量 Java 进行比较

javascript - 分割字符串并保留分割器

python - 正则表达式与值不匹配

python - Python 生成器函数如何维护本地状态?

python - 在Python中追加列表的问题

python - 在 Python 中拆分空字符串时,为什么 split() 返回一个空列表,而 split ('\n' ) 返回 ['']?

python - 使用python反向读取ip地址