serhii.net

In the middle of the desert you can say anything you want

08 Feb 2024

Sorting Ukrainian words in Python

How to sort Ukrainian words in Python

(Як сортувати українські слова, for the soul that may be googling this in the logical language)

Context: first seen in 231203-1745 Masterarbeit LMentry-static-UA task, where I had this:

Серед 'їжа' і 'ліжко', яке слово знаходиться ближче до літери A в алфавіті?
(end of prompt on previous line)
target string or answer choice index (starting on next line):
ліжко
>>> ' '.join(sorted(set("А а, Б б, В в, Г г, Ґ ґ, Д д, Е е, Є є, Ж ж, З з, И и, І і, Ї ї, Й й, К к, Л л, М м, Н н, О о, П п, Р р, С с, Т т, У у, Ф ф, Х х, Ц ц, Ч ч, Ш ш, Щ щ, ь, Ю ю, Я я")))

'  , Є І Ї А Б В Г Д Е Ж З И Й К Л М Н О П Р С Т У Ф Х Ц Ч Ш Щ Ю Я а б в г д е ж з и й к л м н о п р с т у ф х ц ч ш щ ь ю я є і ї Ґ ґ'

Aha.

How to Sort Unicode Strings Alphabetically in Python – Real Python

sudo locale-gen --lang uk
Generating locales (this might take a while)...
  uk_UA.UTF-8... done
Generation complete.

> sudo apt install language-pack-uk
>>> import locale
>>> locale.getlocale()
('en_US', 'UTF-8')
>>> locale.setlocale(locale.LC_COLLATE, "uk_UA.UTF-8")
'uk_UA.UTF-8'

>>> ' '.join(sorted(set("А а, Б б, В в, Г г, Ґ ґ, Д д, Е е, Є є, Ж ж, З з, И и, І і, Ї ї, Й й, К к, Л л, М м, Н н, О о, П п, Р р, С с, Т т, У у, Ф ф, Х х, Ц ц, Ч ч, Ш ш, Щ щ, ь, Ю ю, Я я"), key=locale.strxfrm))
'  , А а Б б В в Г г Ґ ґ Д д Е е Є є Ж ж З з И и І і Ї ї Й й К к Л л М м Н н О о П п Р р С с Т т У у Ф ф Х х Ц ц Ч ч Ш ш Щ щ ь Ю ю Я я'

Bonus/todo: pandas spacy Token vs str sorting

Later I’ll look into this, but a Series of spacy Tokens in two langs gets sorted differently from a series of str.

The first uses a weird order where Latin letters get mixed up with Cyrillic ones, so that English a is close to Ukrainian a.

Nel mezzo del deserto posso dire tutto quello che voglio.