- Python進(jìn)階編程:編寫更高效、優(yōu)雅的Python代碼
- 劉宇宙 謝東 劉艷
- 689字
- 2021-04-30 12:39:40
2.5 將Unicode文本標(biāo)準(zhǔn)化
在處理Unicode字符串時(shí),為了保證字符串的可用性,需要確保所有字符串在底層有相同的表示。
在Unicode字符串中,某些字符能夠用多個(gè)合法的編碼表示,代碼(unicode_standard.py)示例如下:
uni_str_1 = 'Spicy Jalape\u00f1o' uni_str_2 = 'Spicy Jalapen\u0303o' print(uni_str_1) print(uni_str_2) print(uni_str_1 == uni_str_2) print(len(uni_str_1)) print(len(uni_str_2)) 執(zhí)行py文件,輸出結(jié)果如下: Spicy Jalape?o Spicy Jalapen~o False 14 15
示例中的文本Spicy Jalape?o使用了兩種形式來表示。第一種形式使用整體字符“?”(U+00F1),第二種形式使用拉丁字母“n”后面跟一個(gè)“~”的組合字符(U+0303)。
在比較字符串的程序中使用字符的多種表示會(huì)產(chǎn)生問題。為了避免這個(gè)問題的發(fā)生,我們可以使用unicodedata模塊先將文本標(biāo)準(zhǔn)化,代碼(unicode_standard.py)示例如下:
import unicodedata t_1 = unicodedata.normalize('NFC', uni_str_1) t_2 = unicodedata.normalize('NFC', uni_str_2) print(t_1 == t_2) print(ascii(t_1)) t_3 = unicodedata.normalize('NFD', uni_str_1) t_4 = unicodedata.normalize('NFD', uni_str_2) print(t_3 == t_4) print(ascii(t_3))
執(zhí)行py文件,輸出結(jié)果如下:
True 'Spicy Jalape\xf1o' True 'Spicy Jalapen\u0303o'
normalize()第一個(gè)參數(shù)指定了字符串標(biāo)準(zhǔn)化的方式。NFC表示字符由同一種編碼組成,而NFD表示字符可分解為多個(gè)組合字符。
Python同樣支持?jǐn)U展的標(biāo)準(zhǔn)化形式——NFKC和NFKD。它們?cè)谔幚砟承┳址臅r(shí)候增加了額外的兼容特性,代碼(unicode_standard.py)示例如下:
test_str = '\ufb01' print(test_str) print(unicodedata.normalize('NFD', test_str)) print(unicodedata.normalize('NFKD', test_str)) print(unicodedata.normalize('NFKC', test_str))
標(biāo)準(zhǔn)化對(duì)于任何需要以一致的方式處理Unicode文本的程序都是非常重要的,特別是在處理來自用戶輸入的字符串但很難去控制編碼的時(shí)候。
在清理和過濾文本的時(shí)候,字符的標(biāo)準(zhǔn)化也是很重要的。如想清除一些文本上面的變音符(可能是為了搜索和匹配),相關(guān)代碼(unicode_standard.py)示例如下:
test_1 = unicodedata.normalize('NFD', uni_str_1) print(''.join(c for c in test_1 if not unicodedata.combining(c)))
執(zhí)行py文件,輸出結(jié)果如下:
Spicy Jalapeno
該示例展示了unicodedata模塊的另一個(gè)重要方面——測試字符類的工具函數(shù)。combining()函數(shù)可以測試一個(gè)字符是否為和音字符。這個(gè)模塊中的其他函數(shù)可用于查找字符類別、測試字符是否為數(shù)字字符等。
Unicode是一個(gè)很大的主題。讀者如果想更深入地了解關(guān)于標(biāo)準(zhǔn)化方面的信息,可以到Unicode官網(wǎng)查找更多相關(guān)信息。
- AngularJS入門與進(jìn)階
- Apache Spark 2 for Beginners
- Python神經(jīng)網(wǎng)絡(luò)項(xiàng)目實(shí)戰(zhàn)
- aelf區(qū)塊鏈應(yīng)用架構(gòu)指南
- Reactive Programming With Java 9
- SQL Server 2012數(shù)據(jù)庫管理與開發(fā)項(xiàng)目教程
- .NET 3.5編程
- BeagleBone Black Cookbook
- NGINX Cookbook
- 區(qū)塊鏈國產(chǎn)化實(shí)踐指南:基于Fabric 2.0
- 動(dòng)手打造深度學(xué)習(xí)框架
- SignalR:Real-time Application Development(Second Edition)
- Ext JS 4 Plugin and Extension Development
- Android高級(jí)開發(fā)實(shí)戰(zhàn):UI、NDK與安全
- Python應(yīng)用開發(fā)技術(shù)