Python實現把utf-8格式的檔案轉換成gbk格式的檔案

來源:互聯網
上載者:User
需求:將utf-8格式的檔案轉換成gbk格式的檔案

實現代碼如下:

代碼如下:


def ReadFile(filePath,encoding="utf-8"):
with codecs.open(filePath,"r",encoding) as f:
return f.read()

def WriteFile(filePath,u,encoding="gbk"):
with codecs.open(filePath,"w",encoding) as f:
f.write(u)

def UTF8_2_GBK(src,dst):
content = ReadFile(src,encoding="utf-8")
WriteFile(dst,content,encoding="gbk")

代碼講解:

函數ReadFile的第二個參數指定以utf-8格式的編碼方式讀取檔案,返回的結果content為Unicode然後,在將Unicode以gbk格式寫入檔案中。

這樣就能實現需求。
但是,如果要轉換格式的檔案中包含有一些字元並不包含在gbk字元集中的話,就會報錯,類似如下:

代碼如下:


UnicodeEncodeError: 'gbk' codec can't encode character u'\xa0' in position 4813: illegal multibyte sequence


以上的報錯資訊的意思是:在將Unicode編碼成gbk的時候,不能將Unicode u'\xa0'編碼成gbk。

這裡,我們需要弄清楚gb2312、gbk和gb18030三者之間的關係

代碼如下:


GB2312:6763個漢字
GBK:21003個漢字
GB18030-2000:27533個漢字
GB18030-2005:70244個漢字


所以,GBK是GB2312的超集,GB18030是GBK的超集。
理清了關係之後,我們進一步改進下代碼:

代碼如下:


def UTF8_2_GBK(src,dst):
content = ReadFile(src,encoding="utf-8")
WriteFile(dst,content,encoding="gb18030")

運行後,發現沒有報錯,可以正常運行。

因為,在GB18030字元集中,可以找到u'\xa0'對應的字元。
此外,還有另外一種實現方案:
需要修改下WriteFile方法

代碼如下:


def WriteFile(filePath,u,encoding="gbk"):
with codecs.open(filePath,"w") as f:
f.write(u.encode(encoding,errors="ignore"))


這裡,我們將Unicode編碼(encode)成gbk格式,但是注意encode函數的第二個參數,我們賦值"ignore",表示在編碼的時候,忽略掉那些無法編碼的字元,解碼同理。

但是,當我們執行後,發現可以成功的將utf-8格式的檔案修改成了ansi格式。但,另外發現產生的檔案中,每個一行都有一行空行。

這裡,可以指定以二進位流的形式寫檔案,修改後的代碼如下:

代碼如下:


def WriteFile(filePath,u,encoding="gbk"):
with codecs.open(filePath,"wb") as f:
f.write(u.encode(encoding,errors="ignore"))

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.