- ただし、100%正しいわけではない
- 特に「大きなサイズ」のスクリプトは「ascii」で返してくることが多い
- その確率?を示すのが confidence っぽい
"""
ファイルのエンコードを判定する
>python -m pip install chardet
"""
import chardet
import PySimpleGUI as sg
file_p = sg.PopupGetFile("FIle?: ")
with open(file_p, 'rb') as f:
c = f.read()
result = chardet.detect(c)
print(result)
# > {'encoding': 'UTF-8-SIG', 'confidence': 1.0, 'language': ''}
関数-大きなサイズの場合
def get_encoding(file_p: str):
"""
ファイルのエンコードを取得
Para
--------------------------
file_p: str
Return
--------------------------
result_dic: dic
chardetで調べたコード情報(辞書形式)
参考
https://zenn.dev/takedato/articles/c3a491546f8c58
"""
with open(file_p, 'rb') as f:
c = f.read()
result_dic = chardet.detect(c)
return result_dic
def get_encoding_for_bigsize(file_p: str):
"""
ファイルのエンコードを取得(サイズ大用)
Para
--------------------------
file_p: str
Return
--------------------------
result_dic: dic
chardetで調べたコード情報(辞書形式)
"""
with open(file_p, 'rb') as f:
detector = UniversalDetector()
for line in f:
detector.feed(line)
if detector.done:
break
detector.close()
result_dic = detector.result
return result_dic