1. Python での XML ファイルのエンコーディングの問題
1. Python で使用される xml.etree.ElementTree
ライブラリは、標準の UTF-8 形式エンコーディングの解析と生成のみをサポートします
2. GBK
や GB2312
などの一般的な中国語でエンコードされた XML ファイルは、XML が古いシステムで中国語の文字を記録できるようにするために使用されます
3 . XML ファイルの先頭にヘッダーがあります。ヘッダーは、プログラムが XML を処理するときに使用するエンコーディングを指定します。
- バイナリ モードを使用して 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 サイトの他の関連記事を参照してください。

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

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

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

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

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

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

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

Useforloopswhenthenumberofiterationsisknowninadvance、andwhiloopswheniterationsdependonacondition.1)forloopsareidealforsecenceslikelistoranges.2)


ホットAIツール

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

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

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

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

人気の記事

ホットツール

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

ZendStudio 13.5.1 Mac
強力な PHP 統合開発環境

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

WebStorm Mac版
便利なJavaScript開発ツール

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