使用python將用ASCII表示的16進制unicode編碼的ASCII字符串轉換爲unicode字符串

漢字“你”的unicode編碼爲u'/u4F60',將該編碼用ASCII字符表示爲字符串“4F60”。按照這樣的規則將一字符串編碼後,如何還原爲unicode字符串?

可以通過使用兩個Python內置的函數來簡單解決這個問題。
    int( [x [, radix] ]) —— 該函數將字符串x按照指定的進制radix轉換爲數字
    unichr(i) —— 該函數返回一個字符的unicode字符串,該字符的unicode編碼是整數i
則有:

>>>print unichr(int('4F60'16))

由此,利用下面的函數,字符串“4F6060F354034EC04E48FF1F621160F3572895474E0A901B901BFF01" 可解析爲“你想吃什麼?我想在鎮上逛逛!”

def ucps2str(ucpstr):
    
''''Convert unicode code point (in hex) ascii string to unicode string'''
    s 
= ''
    
for i in range(len(ucpstr)/4):
        ucp 
= ucpstr[i*4:i*4+4]
        s 
= s + unichr(int(ucp, 16))

    
return s

if __name__ == '__main__':
    ucps 
= '4F6060F354034EC04E48FF1F621160F3572895474E0A901B901BFF01'
    
print "Original:  %s " % ucps
    
print "Converted:  %s " % ucps2str(ucps)

關於unicode和Python中unicode的相關內容,可參考如下鏈接:
1) The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) Joel Spolsky關於unicode概念的文章,入門必讀。

2) All About Python and Unicode Python中的unicdoe

3) How to Use UTF-8 with Python Python中使用UTF-8,以及Unicode文件的處理

4) 談談Unicode編碼,簡要解釋UCS、UTF、BMP、BOM等名詞 解釋了很多概念

5) Unicode for Programmers 有部分關於Python和Unicode的內容

6) The Basics of UTF-8 詳細介紹了UTF-8編碼的方法,有相關代碼

7) The Complete Guide to C++ Strings, Part I - Win32 Character Encodings 介紹了我永遠都搞不懂的Windows下的字符編碼
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章