Unicode文字排序和Unicode資料庫

2021-10-07 20:13:19 字數 3112 閱讀 8737

python比較任何型別的序列時,會一一比較序列裡的各個元素。

字串來說,比較的是碼位

對於非ascii字元比較時, 非ascii文字的標準排序方式是使用locale.strxfrm函式

使用locale.strxfrm函式之前,必須先為應用設定合適的區域設定

>>

>

import locale

>>

> locale.setlocale(locale.lc_collate,

'pt_br.utf-8'

)'pt_br.utf-8'

>>

> fruits =

['caju'

,'atemoia'

,'cajá'

,'açaí'

,'acerola'

]>>

> sorted_fruits =

sorted

(fruits, key=locale.strxfrm)

>>

> sorted_fruits

['açaí'

,'acerola'

,'atemoia'

,'cajá'

,'caju'

]

其中有幾點要注意

james tauber 開發了pyuca庫,這是unicode排序演算法(unicode collation algorithm uca)的純python實現。

#使用pyuca.collator.sort_key方法

>>

>

import pyuca

>>

> coll = pyuca.collator(

)>>

> fruits =

['caju'

,'atemoia'

,'cajá'

,'açaí'

,'acerola'

]>>

> sorted_fruits =

sorted

(fruits, key=coll.sort_key)

>>

> sorted_fruits

['açaí'

,'acerola'

,'atemoia'

,'cajá'

,'caju'

]

unicode標準提供了乙個完整的資料庫(許多格式化的文字檔案),不僅包括碼位與字元名稱之間的對映,還有各個字元的元資料,以及字元之間的關係。

unicodedata模組中有幾個函式用於獲取字元的元資料。

#unicode資料庫中數值字元的元資料示例(各個標號說明輸出中的各列)

import unicodedata

import re

re_digit = re.

compile

(r'\d')

sample =

'1\xbc\xb2\u0969\u136b\u216b\u2466\u2480\u3285'

for char in sample:

print

('u+%04x'

%ord

(char)

, ➊

char.center(6)

, ➋

're_dig'

if re_digit.match(char)

else

'-', ➌

'isdig'

if char.isdigit(

)else

'-', ➍

'isnum'

if char.isnumeric(

)else

'-', ➎

format

(unicodedata.numeric(char)

,'5.2f'

), ➏

unicodedata.name(char)

, ➐

sep=

'\t'

)

➊ u+0000格式的碼位。

➋ 在長度為6的字串中居中顯示字元。

➌ 如果字元匹配正規表示式r』\d』,顯示re_dig。

➍ 如果char.isdigit()返回true,顯示isdig。

➎ 如果char.isnumeric()返回true,顯示isnum。

➏ 使用長度為5、小數點後保留2位的浮點數顯示數值。

➐ unicode標準中字元的名稱。

輸出

u+

0031

1 re_dig isdig isnum 1.00 digit one

u+00bc ¼ -

- isnum 0.25 vulgar fraction one quarter

u+00b2 ² - isdig isnum 2.00 superscript two

u+0969 ३ re_dig isdig isnum 3.00 devanagari digit three

u+136b ፫ - isdig isnum 3.00 ethiopic digit three

u+216b ⅻ -

- isnum 12.00 roman numeral twelve

u+2466 ⑦ - isdig isnum 7.00 circled digit seven

u+2480 ⒀ -

- isnum 13.00 parenthesized number thirteen

u+3285 ㊅ -

- isnum 6.00 circled ideograph six=

分析:第6列是在字元上呼叫unicodedata.numeric(char)函式得到的結果。這表明,unicode知道表示數字的符號的數值。

C 讀寫unicode文字

熟悉一下字元型別,char,wchar t,tchar,最熟悉的char是單位元組字元,適用於ansi編碼 wchar t是雙位元組的寬字元型別,適用於unicode編碼 tchar是乙個巨集,在ansi壞境下定義為char,unicode壞境下定義為wchar t。怎麼來表示字串?對,字元陣列,要...

用C 讀寫unicode文字

用c 讀寫unicode文字 致敬原作者 http librawill.blogspot.com 2008 08 cunicode 2881.html 熟悉一下字元型別,char,wchar t,tchar,最熟悉的char是單位元組字元,適用於ansi編碼 wchar t是雙位元組的寬字元型別,適...

用C 讀寫unicode文字

字元型別 char,wchar t,tchar,最熟悉的char是單位元組字元,適用於ansi編碼 wchar t是雙位元組的寬字元型別,適用於unicode編碼 tchar是乙個巨集,在ansi壞境下定義為char,unicode壞境下定義為wchar t。怎麼來表示字串?對,字元陣列,要知道在c...