検索
ホームページバックエンド開発Python チュートリアルPython で XML ファイルのエンコーディングを変換する方法

1. Python での XML ファイルのエンコーディングの問題

1. Python で使用される xml.etree.ElementTree ライブラリは、標準の UTF-8 形式エンコーディングの解析と生成のみをサポートします

2. GBKGB2312 などの一般的な中国語でエンコードされた XML ファイルは、XML が古いシステムで中国語の文字を記録できるようにするために使用されます

3 . XML ファイルの先頭にヘッダーがあります。ヘッダーは、プログラムが XML を処理するときに使用するエンコーディングを指定します。

Python で XML ファイルのエンコーディングを変換する方法

4. エンコーディングを変更するには、変更する必要があります。ファイル全体のエンコードのみを変更する必要があり、識別ヘッダーのエンコード部分の値も変更する必要があります。

2. Python XML ファイルを処理するためのアイデア

1. 読み取りとデコード:
  • バイナリ モードを使用して XML ファイルを読み取り、ファイルをバイナリ ストリームに変換します。
  • #.encode()# を使用します。 ## バイナリ ストリームを元のファイルのエンコード形式に変換するメソッド 文字列

2 に解析されます。識別ヘッダーを処理します: .replace()## を使用します。 # 文字列 #Part 内の 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 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事は亿速云で複製されています。侵害がある場合は、admin@php.cn までご連絡ください。
Python:編集と解釈に深く掘り下げますPython:編集と解釈に深く掘り下げますMay 12, 2025 am 12:14 AM

pythonusesahybridmodelofcompilation andtertation:1)thepythoninterpretercompilessourcodeodeplatform-indopent bytecode.2)thepythonvirtualmachine(pvm)thenexecuteTesthisbytecode、balancingeaseoputhswithporformance。

Pythonは解釈されたものですか、それとも編集された言語であり、なぜそれが重要なのですか?Pythonは解釈されたものですか、それとも編集された言語であり、なぜそれが重要なのですか?May 12, 2025 am 12:09 AM

pythonisbothintersedand compiled.1)it'scompiledtobytecode forportabalityacrossplatforms.2)bytecodeisthenは解釈され、開発を許可します。

ループ対pythonのループの場合:説明されたキーの違いループ対pythonのループの場合:説明されたキーの違いMay 12, 2025 am 12:08 AM

loopsareideal whenyouwhenyouknumberofiterationsinadvance、foreleloopsarebetterforsituationsは、loopsaremoreedilaConditionismetを使用します

ループのために:実用的なガイドループのために:実用的なガイドMay 12, 2025 am 12:07 AM

henthenumber ofiterationsisknown advanceの場合、dopendonacondition.1)forloopsareideal foriterating over for -for -for -saredaverseversives likelistorarrays.2)whileopsaresupasiable forsaresutable forscenarioswheretheloopcontinupcontinuspificcond

Python:それは本当に解釈されていますか?神話を暴くPython:それは本当に解釈されていますか?神話を暴くMay 12, 2025 am 12:05 AM

pythonisnotpurelyLepted; itusesahybridapproachofbytecodecodecodecodecodecodedruntimerttation.1)pythoncompilessourcodeintobytecode、whodythepythonvirtualmachine(pvm).2)

同じ要素を持つPython Concatenateリスト同じ要素を持つPython ConcatenateリストMay 11, 2025 am 12:08 AM

ToconcatenateListsinpythothesheElements、使用:1)Operatortokeepduplicates、2)asettoremoveduplicates、or3)listcomplunting for controloverduplicates、各メトドハスディフェルフェルフェントパフォーマンスアンドソーダーインプリテーション。

解釈対編集言語:Pythonの場所解釈対編集言語:Pythonの場所May 11, 2025 am 12:07 AM

pythonisantertedlanguage、useaseofuseandflexibility-butfactingporformantationationsincriticalapplications.1)解釈されたlikepythonexecuteline-by-lineを解釈します

ループのために:Pythonでそれぞれを使用するのはいつですか?ループのために:Pythonでそれぞれを使用するのはいつですか?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance、andwhiloopswheniterationsdependonacondition.1)forloopsareidealforsecenceslikelistoranges.2)

See all articles

ホットAIツール

Undresser.AI Undress

Undresser.AI Undress

リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover

AI Clothes Remover

写真から衣服を削除するオンライン AI ツール。

Undress AI Tool

Undress AI Tool

脱衣画像を無料で

Clothoff.io

Clothoff.io

AI衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

SublimeText3 Linux 新バージョン

SublimeText3 Linux 新バージョン

SublimeText3 Linux 最新バージョン

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強力な PHP 統合開発環境

SecLists

SecLists

SecLists は、セキュリティ テスターの究極の相棒です。これは、セキュリティ評価中に頻繁に使用されるさまざまな種類のリストを 1 か所にまとめたものです。 SecLists は、セキュリティ テスターが必要とする可能性のあるすべてのリストを便利に提供することで、セキュリティ テストをより効率的かつ生産的にするのに役立ちます。リストの種類には、ユーザー名、パスワード、URL、ファジング ペイロード、機密データ パターン、Web シェルなどが含まれます。テスターはこのリポジトリを新しいテスト マシンにプルするだけで、必要なあらゆる種類のリストにアクセスできるようになります。

WebStorm Mac版

WebStorm Mac版

便利なJavaScript開発ツール

PhpStorm Mac バージョン

PhpStorm Mac バージョン

最新(2018.2.1)のプロフェッショナル向けPHP統合開発ツール