yamamoto-ryuzo / TokyoOD_downloader

0 stars 0 forks source link

文字コード NON の時の挙動を見直し #8

Closed yamamoto-ryuzo closed 3 weeks ago

yamamoto-ryuzo commented 1 month ago

思ったより文字コードNONが多いため、対応策を検討

yamamoto-ryuzo commented 1 month ago

一度「ftfy」で対応!

yamamoto-ryuzo commented 3 weeks ago

とりあえず以下で対応

                  ######## エンコードの確認 #########
                    # バイナリモードでファイルを開く
                    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}のエンコーディングを判定できませんでした。")