python encode

在作業系統上都有預設語言,例如windows上預設可能是big5,linux則是utf8。當python要轉換編碼的時候,可以使用encode,但是有個先決條件,必須要先把編碼轉換成作業系統的預設語言

以linux為例,要轉成big5,需先decode成utf8,在encode成big5:

1
2
3
4
5
6
# -*- coding: utf-8 -*-

u_hello = "哈囉".decode("utf8")
big5_hello = u_hello.encode("big5")

print big5_hello

接著將轉換過得字串寫入到檔案,在用gedit、word…之類的軟體,以big5編碼開啟就能看到剛剛寫入文字。

1
2
3
4
#write to file
f = open( "big5_text.txt", "w" )
f.write( big5_hello )
f.close()

另外在字串前面加個u,和decode成utf8相同:

1
2
3
4
5
6
7
8
9
10
11
>>> u"哈囉" == "哈囉".decode("utf8")
True

>>> type("哈囉")
<type 'str'>

>>> type(u"哈囉")
<type 'unicode'>

>>> type("哈囉".decode("utf8"))
<type 'unicode'>

如果是windows的作業系統,只要先將decode成big5,即可轉成其他編碼。