Python

Python 的 Big5 與 UTF-8 檔案編碼轉換程式教學

介紹如何使用簡單的 Python 程式處理 Big5 與 UTF-8 檔案的編碼轉換問題。

Big5 與 UTF-8 的編碼轉換是在中文資料處理上常見的問題之一,以下介紹如何使用 Python 來處理 Big5 與 UTF-8 編碼的互轉。

Big5 轉 UTF-8

Python 的讀取與寫入檔案函數本身就有支援各種編碼,所以只要在開啟檔案時,正確指定檔案的編碼,就可以讓 Python 自動處理編碼轉換問題,以下是 Big5 檔案轉成 UTF-8 檔案的範例。

# 開啟 Big5 輸入檔案
inFile = open("big5_input.txt", "r", encoding = "Big5")

# 開啟 UTF-8 輸出檔案
outFile = open("utf8_output.txt", "w", encoding = "UTF-8")

# 以 Big5 編碼讀取檔案
content = inFile.read()

# 以 UTF-8 編碼寫入檔案
outFile.write(content)

# 關閉檔案
inFile.close()
outFile.close()

檔案轉換編碼之後,結果會像這樣,編碼改變而內容維持不變。

Big5 轉 UTF-8

這是使用 with 的寫法,跟上面那段程式碼比較起來,作用完全相同,只不過寫法比較簡潔。

# 使用 with 的寫法
with open("big5_input.txt", "r", encoding = "Big5") as inFile, open("utf8_output.txt", "w", encoding = "UTF-8") as outFile:
    outFile.write(inFile.read())

UTF-8 轉 Big5

UTF-8 轉 Big5 的程式撰寫方式也是一樣,只是將編碼調換而已,以下是一個簡單的範例。

# 開啟 UTF-8 輸入檔案
inFile = open("utf8_input.txt", "r", encoding = "UTF-8")

# 開啟 Big5 輸出檔案
outFile = open("big5_output.txt", "w", encoding = "Big5")

# 以 UTF-8 編碼讀取檔案
content = inFile.read()

# 以 Big5 編碼寫入檔案
outFile.write(content)

# 關閉檔案
inFile.close()
outFile.close()
UTF-8 轉 Big5

參考資料:OpenHome.cc

Share
Published by
Office Guide

Recent Posts

Python 使用 PyAutoGUI 自動操作滑鼠與鍵盤

本篇介紹如何在 Python ...

9 個月 ago

Ubuntu Linux 以 WireGuard 架設 VPN 伺服器教學與範例

本篇介紹如何在 Ubuntu ...

9 個月 ago

Linux 網路設定 ip 指令用法教學與範例

本篇介紹如何在 Linux 系...

9 個月 ago

Windows 使用 TPM 虛擬智慧卡保護 SSH 金鑰教學與範例

本篇介紹如何在 Windows...

10 個月 ago

Linux 以 Shamir’s Secret Sharing 分割保存金鑰教學與範例

介紹如何在 Linux 中使用...

11 個月 ago

Linux 以 Cryptsetup、LUKS 加密 USB 隨身碟教學與範例

介紹如何在 Linux 系統中...

11 個月 ago