• 跳至主要導覽
  • 跳至主要內容
  • 跳至主要資訊欄
Office 指南

Office 指南

辦公室工作實用教學

  • Excel
  • Word
  • PowerPoint
  • Windows
  • PowerShell
  • R

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
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
UTF-8 轉 Big5

參考資料:OpenHome.cc

分類:Python

主要資訊欄

搜尋

近期文章

  • Python 使用 PyAutoGUI 自動操作滑鼠與鍵盤
  • Ubuntu Linux 以 WireGuard 架設 VPN 伺服器教學與範例
  • Linux 網路設定 ip 指令用法教學與範例
  • Windows 使用 TPM 虛擬智慧卡保護 SSH 金鑰教學與範例
  • Linux 以 Shamir’s Secret Sharing 分割保存金鑰教學與範例
  • Linux 以 Cryptsetup、LUKS 加密 USB 隨身碟教學與範例
  • Linux 以 Cryptsetup 與 LUKS 加密磁碟教學與範例
  • Linux 使用 age 簡潔的加密、解密工具使用教學與範例

推薦網站

  • Udemy 線上教學課程
  • Coursera 線上教學課程

關注本站

  • 電子郵件
  • Facebook

公益

  • 家扶基金會
  • 台灣世界展望會
  • Yahoo 奇摩公益
  • igiving 公益網
  • 兒福聯盟

Copyright © 2021 · Office Guide