python-chardet

python-chardetを使った文字コード推定

使い方

>>> import chardet
>>> s = 'こんにちは'
>>> chardet.detect(s)
{'confidence': 0.9690625, 'encoding': 'utf-8'}
>>> s.decode(chardet.detect(s)['encoding'])
u'\u3053\u3093\u306b\u3061\u306f'

リンク

chardet · PyPI
https://pypi.org/project/chardet/

GitHub – chardet/chardet: Python 2/3 compatible character encoding detector.
https://github.com/chardet/chardet

Pythonでnkf

Pythonで文字コードが不明な文字列(例えばインターネット上のHTMLは文字コードが間違っている場合があります)はnkfを使うと簡単に取り扱うことができるみたいです。

# emerge -pv app-i18n/nkf

These are the packages that would be merged, in order:

Calculating dependencies... done!
[ebuild   R    ] app-i18n/nkf-2.0.7  USE="python -perl"

USEフラグにpythonを付けているとPythonからnkfが使えます。

>>> import nkf
>>> nkf.nkf('-w', 'こんにちは').decode('utf-8')
u'\u3053\u3093\u306b\u3061\u306f'

手軽なので重宝しそうです。