ZIPファイルを解凍した際、wordファイル等が複数ある場合、文字化けしていることはありませんか?
今回はそんな悩みを解決するとともに、自動で文字化けを解除する方法をまとめます。
1. 問題の原因を理解する
ZipファイルにWordデータをまとめると、文字化けが発生する原因は、異なるエンコーディングを持つWordデータが混在していることです。
2. エンコーディングの統一
3. Pythonを使用したバッチ処理
import os
from chardet.universaldetector import UniversalDetector
def detect_encoding(file_path):
detector = UniversalDetector()
with open(file_path, 'rb') as f:
for line in f:
detector.feed(line)
if detector.done:
break
detector.close()
return detector.result['encoding']
with open(file_path, 'r', encoding=detect_encoding(file_path), errors='replace') as f:
content = f.read()
with open(file_path, 'w', encoding=target_encoding) as f:
f.write(content)
# ディレクトリ内のWordファイルを一括で処理
for filename in os.listdir(directory_path):
if filename.endswith(".docx"):
file_path = os.path.join(directory_path, filename)
convert_encoding(file_path)