如何在Python中按字母顺序排序Unicode字符串?
Python 默认是按照字节值来排序的,这就意味着像 é 这样的字母会排在 z 之后,还有一些其他奇怪的排序情况。那么,在 Python 中,怎样才能按字母顺序来排序呢?
有没有什么库可以做到这一点?我找不到相关的东西。最好是排序能支持不同语言,这样它就能理解在瑞典语中,å、ä、ö 应该排在 z 之后,而 ü 应该排在 u 的前面等等。因此,支持 Unicode 几乎是必须的。
如果没有这样的库,最好的办法是什么呢?是不是可以把每个字母映射到一个整数值,然后把字符串转换成一个整数列表来进行排序呢?
11 个回答
10
试试James Tauber的Python Unicode 排序算法。虽然它可能不完全符合你的需求,但值得一看。想了解更多相关问题的信息,可以看看Christopher Lenz的这篇文章。
59
我在回答里没看到这个。我的应用程序使用Python的标准库根据地区设置进行排序。这非常简单。
# python2.5 code below
# corpus is our unicode() strings collection as a list
corpus = [u"Art", u"Älg", u"Ved", u"Wasa"]
import locale
# this reads the environment and inits the right locale
locale.setlocale(locale.LC_ALL, "")
# alternatively, (but it's bad to hardcode)
# locale.setlocale(locale.LC_ALL, "sv_SE.UTF-8")
corpus.sort(cmp=locale.strcoll)
# in python2.x, locale.strxfrm is broken and does not work for unicode strings
# in python3.x however:
# corpus.sort(key=locale.strxfrm)
问问Lennart和其他回答者:难道没有人知道'locale'这个东西,还是说它不适合这个任务?
87
IBM的ICU库可以做到这一点(还有很多其他功能)。它有Python的接口:PyICU。
更新:ICU和locale.strcoll
在排序上的主要区别是,ICU使用完整的Unicode 排序算法,而strcoll
使用的是ISO 14651。
这两种算法之间的区别在这里简单总结了一下:http://unicode.org/faq/collation.html#13。这些区别是一些比较特殊的情况,在实际应用中很少会遇到。
>>> import icu # pip install PyICU
>>> sorted(['a','b','c','ä'])
['a', 'b', 'c', 'ä']
>>> collator = icu.Collator.createInstance(icu.Locale('de_DE.UTF-8'))
>>> sorted(['a','b','c','ä'], key=collator.getSortKey)
['a', 'ä', 'b', 'c']