欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python 中對 XML 文件的編碼轉(zhuǎn)換問題

 更新時間:2023年03月21日 09:45:54   作者:Lilixxs  
這篇文章主要介紹了Python 中對 XML 文件的編碼轉(zhuǎn)換問題,本文給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

1. 在 Python 中 XML 文件的編碼問題

1.Python 使用的xml.etree.ElementTree庫只支持解析和生成標(biāo)準(zhǔn)的UTF-8格式的編碼

2.常見GBKGB2312等中文編碼的 XML 文件,用以在老舊系統(tǒng)中保證 XML 對中文字符的記錄能力

3.XML 文件開頭有標(biāo)識頭,標(biāo)識頭指定了程序處理 XML 時應(yīng)該使用的編碼

在這里插入圖片描述

4.要修改編碼,不僅要修改文件整體的編碼,還要將標(biāo)識頭中 encoding 部分的值修改

2. 處理 Python XML 文件的思路

1.讀取&解碼:

  • 使用二進(jìn)制模式讀取 XML 文件,將文件變?yōu)槎M(jìn)制流
  • 將二進(jìn)制流使用.encode()方法,使用原文件的編碼格式進(jìn)行解析為字符串

2.處理標(biāo)識頭:使用.replace()方法,替換字符串中的encoding="xxx"部分

3.編碼&保存:將字符串使用新的編碼格式進(jìn)行保存

3. 實際過程中遇到的問題

  • GB2312 <–> UTF:無問題,可直接按照上面的邏輯處理
  • GBK <–> UTF8
    • GBK --> UTF8:無問題,可直接按照上面的邏輯處理
    • UTF8 --> GBK:.encode()會報錯,要加上error="ignore"參數(shù),忽略無法轉(zhuǎn)換的字符
    • 這里的原理是:GBK 編碼兼容 UTF-8 編碼,因此無法轉(zhuǎn)換的內(nèi)容使用 GBK 直接也能顯示
  • GBK <–> GB2312:無問題

4. 最后使用的代碼

# filepath -- 原文件路徑
# savefilepath -- 轉(zhuǎn)換后文件存儲路徑(默認(rèn) = 原文件路徑)
# oldencoding -- 原文件的編碼格式
# newencoding -- 轉(zhuǎn)換后文件的編碼格式
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
    # 出現(xiàn)錯誤時忽略 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
    # 出現(xiàn)錯誤時忽略 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, savefilepath1, 'GBK', 'utf-8')
# utf-8 --> gb2312
convert_xml_encoding(filepath, savefilepath1, 'utf-8', 'gb2312')
# GBK --> gb2312
convert_xml_encoding(filepath, savefilepath1, 'GBK', 'gb2312')

注意事項:

  • 由于這里需要直接替換標(biāo)識頭,要求編碼名稱一定得完全匹配,否則替換會失敗
  • 如:GBK 不能寫成 gbk,utf-8 不能寫成 UTF8此代碼僅在以上 GBK、GB2312、UTF-8 & 常用中英文基礎(chǔ)上測試,其他的編碼格式不保證一定能轉(zhuǎn)換成功

到此這篇關(guān)于Python 中對 XML 文件的編碼轉(zhuǎn)換的文章就介紹到這了,更多相關(guān)Python XML 文件編碼轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論