2015/08/11

Python String List Chinese Encode Decode 中文編碼解碼

最近要在 Python 內使用中文,就開始研究顯示中文的方法。

在 Python 內設計 Unicode 這個超級容器物件,能用來顯示各類、各樣的字元。同時,Unicode 物件也是一個萬用編碼器,只要善用這個物件的能力,就能解決轉碼問題。

Python 編碼宣告


Python 預設使用 Unicode 編碼,如果要使用其他編碼,就必須在程式的頂部加入編碼的宣告,才能讓 Python 直譯器能正確地解析我們在程式碼裡寫的其他文字。我試過能運作的編碼宣告如下:
# -*- coding: utf8 -*-
# coding: utf8


如果忘記加上編碼的宣告就在程式內使用中文的話,會出現類似下面的錯誤:
SyntaxError: Non-ASCII character '\xe5' in file test3.py on line 3, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

Python 印出中文字串


在範例裏,我們有兩種方式可以印出中文字串:
  • 直接印出宣告 Unicode 的變數
  • 使用 unicode 的 .encode 函數以 UTF-8 編碼 String 印出

另外,在範例裏有特別說明 Python 的編碼或解碼:
  • 透過 encode 函數把 Unicode 編碼成 String;
  • 或 decode 函數把 String 解碼成 Unicode。

此外,我們在範例裏使用 UTF-8 編碼印中文,是因為 UTF-8 編碼印中文有幾個優點:
  • UTF-8 兼容 ASCII;
  • 不同於繁體的 Big5 只能編碼中文,UTF-8 能編碼任何 Unicode 支援的文字。
  • UTF-8 為了能夠表達足夠的文字,因此採取動態長度編碼,也就是每個字會由幾個 byte 組成並非固定的。

最後,要特別注意的是《瞭解Unicode》中有提到 Python2 和 Python3 在 Unicode 上的重要差別:
在Python3因為字串已經全部統一成 unicode ,所以不必加上 u ,這是Python2和Python3的重要差別之一,需要特別注意

#!/usr/bin/env python
# -*- coding: utf8 -*-

print '直接印出 Unicode 一'

msg = u'直接印出 Unicode 二'
print msg

msg2 = u'Unicode 編碼 UTF-8 String 一'
encoded = msg2.encode('utf8')
print encoded

print u'Unicode 編碼 UTF-8 String 二'.encode('utf8')

msg3 = 'UTF-8 String \xe8\xa7\xa3\xe7\xa2\xbc Unicode'
decoded = msg3.decode('utf8')
print decoded


JosedeMacBook-Pro:python sunjose$ python test3.py
直接印出 Unicode 一
直接印出 Unicode 二
Unicode 編碼 UTF-8 String 一
Unicode 編碼 UTF-8 String 二
UTF-8 String 解碼 Unicode


Python 印出中文 List


在範例裏,我們有兩種方式可以印出中文 List:
  • 使用 decode('string_escape') 達成
  • 使用 uniout 達成
  • 可以使用以下命令安裝$ sudo -H pip install uniout
  • 使用 _uniout 達成

安裝 uniout 後要記得在 UTF-8 編碼宣告下加入:
import uniout

使用 _uniout 時記得在 UTF-8 編碼宣告下加入:
import _uniout

#!/usr/bin/env python
# -*- coding: utf8 -*-
import uniout
import _uniout

a = ['中文', 'English', 4, [123,456]]
print str(a).decode('string_escape')
print a
print _uniout.unescape(str(a), 'utf8')


JosedeMacBook-Pro:python sunjose$ python test4.py
['中文', 'English', 4, [123, 456]]
['中文', 'English', 4, [123, 456]]
['中文', 'English', 4, [123, 456]]



沒有留言:

張貼留言