Python chardetライブラリで文字列のエンコーディングを取得する方法
環境
Python 3.9.13
Windows 10 Home 64bit
PyCharm 2022.2.1 (Community Edition)
構文
1.「chardet」ライブラリをインストールします
pip install chardet
2. chardet.detect(文字列)
chardet.detect()関数を使って文字列の文字コードを取得します。
使用例
import chardet
def funA(str):
#文字コードの取得
res = chardet.detect(str)
return res['encoding']
#文字コードをUTF-8に変換
str = 'テスト'.encode('utf-8')
print(funA(str))
#文字コードをshift_jisに変換
strB = 'あいうえお'.encode('shift_jis')
print(funA(strB))
実行結果
utf-8
Windows-1252