搜尋
首頁後端開發Python教學Python中怎麼對XML檔案的編碼進行轉換

1. 在Python 中XML 檔案的編碼問題

1.Python 使用的xml.etree.ElementTree函式庫只支援解析與產生標準的UTF-8格式的編碼

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

#3.XML 檔案開頭有標識頭,標識頭指定了程式處理XML 時應該使用的編碼

Python中怎麼對XML檔案的編碼進行轉換

4.要修改編碼,不僅要修改檔案整體的編碼,也要將標識頭中encoding 部分的值修改

2. 處理Python XML 檔案的想法

1.讀取&解碼:

  • 使用二進位模式讀取XML 文件,將文件變為二進位流

  • 將二進位流使用.encode()方法,使用原始文件的編碼格式進行解析為字串

2.處理識別頭:使用.replace()方法,取代字串中的encoding="xxx"#​​# #部分

3.編碼&儲存:將字串使用新的編碼格式進行儲存

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

  • GB2312 UTF:無問題,可直接依照上面的邏輯處理

  • GBK UTF8

    • #GBK --> UTF8:無問題,可直接依照上面的邏輯處理

    • UTF8 --> GBK:.encode()會報錯,要加上error="ignore"參數,忽略無法轉換的字元

    • 這裡的原理是:GBK 編碼相容UTF-8 編碼,因此無法轉換的內容使用GBK 直接也能顯示

  • GBK GB2312:無問題

4. 最後使用的程式碼

# 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刪除
Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解釋嗎?揭穿神話Python:它是真正的解釋嗎?揭穿神話May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

與同一元素的Python串聯列表與同一元素的Python串聯列表May 11, 2025 am 12:08 AM

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

解釋與編譯語言:Python的位置解釋與編譯語言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循環時:您什麼時候在Python中使用?循環時:您什麼時候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能