開発したアプリなど一覧

Pythonで文字コードの自動判別を行うライブラリ

アフィリエイトリンクを含む場合があります

文字コードの判別に何か良い物ないかなーと思ってたらライブラリを発見したので使ってみた。

Universal Encoding Detector

サポートしている文字コードはドキュメント内 Supported encodings にもあるけど以下の通り。

Big5, GB2312/GB18030, EUC-TW, HZ-GB-2312, and ISO-2022-CN (Traditional and Simplified Chinese)
EUC-JP, SHIFT_JIS, and ISO-2022-JP (Japanese)
EUC-KR and ISO-2022-KR (Korean)
KOI8-R, MacCyrillic, IBM855, IBM866, ISO-8859-5, and windows-1251 (Russian)
ISO-8859-2 and windows-1250 (Hungarian)
ISO-8859-5 and windows-1251 (Bulgarian)
windows-1252
ISO-8859-7 and windows-1253 (Greek)
ISO-8859-8 and windows-1255 (Visual and Logical Hebrew)
TIS-620 (Thai)
UTF-32 BE, LE, 3412-ordered, or 2143-ordered (with a BOM)
UTF-16 BE or LE (with a BOM)
UTF-8 (with or without a BOM)
ASCII

以下導入とテスト
Pythonのバージョンによりダウンロードするファイルが違うぐらいで特に問題なく導入できました。

サンプルスクリプトにあった lambda 文が気に入ったのでそのまま使ってしまう。Python で lambda 使った事無いので・・・

$ wget http://chardet.feedparser.org/download/python2-chardet-1.0.1.tgz $ tar zxvf python2-chardet-1.0.1.tgz $ cd python2-chardet-1.0.1 $ sudo python setup.py install $ python Python 2.6.2 (release26-maint, Apr 19 2009, 01:56:41) [GCC 4.3.3] on linux2 Type "help", "copyright", "credits" or "license" for more information.

>>> import chardet >>> chardet.detect('あいうえお') {'confidence': 0.96906250000000005, 'encoding': 'utf-8'} >>> >>> #短すぎると精度が落ちる様だ。 >>> chardet.detect('あ') {'confidence': 0.505, 'encoding': 'utf-8'} >>> >>> import urllib >>> urlread = lambda url: urllib.urlopen(url).read() >>> chardet.detect(urlread('http://google.co.jp')) {'confidence': 1, 'encoding': 'SHIFT_JIS'} >>> chardet.detect(urlread('http://jkl.lomo.jp')) {'confidence': 0.98999999999999999, 'encoding': 'utf-8'}

Sponsored Link

コメント

タイトルとURLをコピーしました