Closed yamamoto-ryuzo closed 3 weeks ago
一度「ftfy」で対応!
とりあえず以下で対応
######## エンコードの確認 #########
# バイナリモードでファイルを開く
with open(f'{download_dir+file_name}', 'rb') as f:
content = f.read()
result = chardet.detect(content)
print(f"Detected Encoding: {result['encoding']}, Confidence: {result['confidence']}")
######## エンコーディングの検証 #########
encoding = result['encoding']
common_encodings = ['utf-8', 'shift_jis', 'euc-jp', 'iso-2022-jp', 'cp932']
if encoding is None or encoding == 'NON' or result['confidence'] < 0.7:
print(f"{download_dir+file_name}のエンコーディングを再検証します。")
for enc in common_encodings:
try:
with open(f'{download_dir+file_name}', 'r', encoding=enc) as f:
text = f.read()
encoding = enc
print(f"エンコーディングを{enc}と判定しました。")
break
except UnicodeDecodeError:
continue
else:
print(f"{download_dir+file_name}のエンコーディングを判定できませんでした。")
思ったより文字コードNONが多いため、対応策を検討