localizing a sort

Ricardo Aráoz ricaraoz at gmail.com
Sun Sep 2 17:19:33 CEST 2007


Peter Otten wrote:
> Am Sat, 01 Sep 2007 18:56:38 -0300 schrieb Ricardo Aráoz:
> 
>> Hi, I've been working on sorting out some words.
>>
>> My locale is :
>>>>> import locale
>>>>> locale.getdefaultlocale()
>> ('es_AR', 'cp1252')
>>
>> I do :
>>>>> a = 'áéíóúäëïöüàèìòù'
>>>>> print ''.join(sorted(a, cmp=lambda x,y: locale.strcoll(x,y)))
>> aeiouàáäèéëìíïòóöùúü
> 
> The lambda is superfluous. Just write cmp=locale.strcoll instead.

No it is not :
>>> print ''.join(sorted(a, cmp=locale.strcoll(x,y)))
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: strcoll expected 2 arguments, got 0

You need the lambda to assign both arguments.

>  
>> This is not what I am expecting. I was expecting :
>> aáàäeéèëiíìï.....etc.
>>
>> The reason is that if you want to order some words (say for a dictionary
>> (paper dict, where you look up words)) this is what happens :
>>>>> a = 'palàbra de pàlabra de pblabra'
>>>>> print ' '.join(sorted(a.split(), cmp=lambda x,y: locale.strcoll(x, y)))
>> de de palàbra pblabra pàlabra
>>
>> While any human being would expect :
>>
>> de de palàbra pàlabra pblabra
>>
>> Does anybody know a way in which I could get the desired output?
> 
> I suppose it would work on your machine if you set the locale first with
> 
>>>> locale.setlocale(locale.LC_ALL, "")

This works. Thanks Peter.




More information about the Python-list mailing list