Python中怎麼對XML檔案的編碼進行轉換
python
xml
1. 在Python 中XML 檔案的編碼問題
1.Python 使用的xml.etree.ElementTree
函式庫只支援解析與產生標準的UTF-8格式的編碼
2.常見GBK
或GB2312
等中文編碼的XML 文件,用以在老舊系統中保證XML 對中文字元的記錄能力
#3.XML 檔案開頭有標識頭,標識頭指定了程式處理XML 時應該使用的編碼
4.要修改編碼,不僅要修改檔案整體的編碼,也要將標識頭中encoding 部分的值修改
2. 處理Python XML 檔案的想法
1.讀取&解碼:
使用二進位模式讀取XML 文件,將文件變為二進位流
將二進位流使用
.encode()
方法,使用原始文件的編碼格式進行解析為字串
2.處理識別頭:使用.replace()
方法,取代字串中的encoding="xxx"## #部分
- GB2312 UTF:無問題,可直接依照上面的邏輯處理
- GBK UTF8
- #GBK --> UTF8:無問題,可直接依照上面的邏輯處理
- UTF8 --> GBK:.encode()會報錯,要加上error="ignore"參數,忽略無法轉換的字元
- 這裡的原理是:GBK 編碼相容UTF-8 編碼,因此無法轉換的內容使用GBK 直接也能顯示
- GBK GB2312:無問題
# filepath -- 原文件路径
# savefilepath -- 转换后文件存储路径(默认 = 原文件路径)
# oldencoding -- 原文件的编码格式
# newencoding -- 转换后文件的编码格式
def convert_xml_encoding(filepath, savefilepath=filepath, oldencoding, newencoding):
# Read the XML file
with open(filepath, 'rb') as file:
content = file.read()
# Decode the content from old encoding
# 出现错误时忽略 errors='ignore'
decoded_content = content.decode(oldencoding, errors='ignore')
# decoded_content = content.decode('GBK')
# Update the encoding in the XML header
updated_content = decoded_content.replace('encoding="{}"'.format(oldencoding),
'encoding="{}"'.format(newencoding))
# Encode the content to new encoding
# 出现错误时忽略 errors='ignore'
encoded_content = updated_content.encode(newencoding,errors='ignore')
# Write the updated content to the file
with open(savefilepath, 'wb') as file:
file.write(encoded_content)
# Result output
print(f"XML file '{os.path.basename(filepath)}'({oldencoding}) --> '{os.path.basename(savefilepath)}'({newencoding})")
# ---------------------- 使用示例 ---------------------
# GBK --> utf-8
convert_xml_encoding(filepath, savefilepath2, 'GBK', 'utf-8')
# utf-8 --> gb2312
convert_xml_encoding(filepath, savefilepath2, 'utf-8', 'gb2312')
# GBK --> gb2312
convert_xml_encoding(filepath, savefilepath2, 'GBK', 'gb2312')
登入後複製
注意事項:
# filepath -- 原文件路径 # savefilepath -- 转换后文件存储路径(默认 = 原文件路径) # oldencoding -- 原文件的编码格式 # newencoding -- 转换后文件的编码格式 def convert_xml_encoding(filepath, savefilepath=filepath, oldencoding, newencoding): # Read the XML file with open(filepath, 'rb') as file: content = file.read() # Decode the content from old encoding # 出现错误时忽略 errors='ignore' decoded_content = content.decode(oldencoding, errors='ignore') # decoded_content = content.decode('GBK') # Update the encoding in the XML header updated_content = decoded_content.replace('encoding="{}"'.format(oldencoding), 'encoding="{}"'.format(newencoding)) # Encode the content to new encoding # 出现错误时忽略 errors='ignore' encoded_content = updated_content.encode(newencoding,errors='ignore') # Write the updated content to the file with open(savefilepath, 'wb') as file: file.write(encoded_content) # Result output print(f"XML file '{os.path.basename(filepath)}'({oldencoding}) --> '{os.path.basename(savefilepath)}'({newencoding})") # ---------------------- 使用示例 --------------------- # GBK --> utf-8 convert_xml_encoding(filepath, savefilepath2, 'GBK', 'utf-8') # utf-8 --> gb2312 convert_xml_encoding(filepath, savefilepath2, 'utf-8', 'gb2312') # GBK --> gb2312 convert_xml_encoding(filepath, savefilepath2, 'GBK', 'gb2312')
登入後複製
- 由於這裡需要直接取代標識頭,要求編碼名稱一定得完全匹配,否則替換會失敗
- 如:GBK不能寫成gbk,utf-8 不能寫成UTF8此程式碼只在以上GBK、GB2312、UTF-8 & 常用中英文基礎上測試,其他的編碼格式不保證一定能轉換成功 #
以上是Python中怎麼對XML檔案的編碼進行轉換的詳細內容。更多資訊請關注PHP中文網其他相關文章!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前
By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
擊敗分裂小說需要多長時間?
3 週前
By DDD
R.E.P.O.保存文件位置:在哪里以及如何保護它?
3 週前
By DDD

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Google AI 為開發者發佈 Gemini 1.5 Pro 和 Gemma 2
