Python」カテゴリーアーカイブ

プログラミング言語「Python」に関するカテゴリーです。

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'

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

Pythonのtypesとassert

Pythonで型チェックの方法です。

types

型の取得には組み込み関数typeを使います。

>>> from types import *
>>> type(1) == IntType
True
>>> type('') == StringType
True
>>> type([]) == ListType
True

assert

C言語など他の言語と同様Pythonにもassertがあります。
assertの直後に評価したい式を書きます。

>>> assert True
>>> assert False
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
AssertionEror

型チェック

typesassertを組み合わせて型チェックができます。

>>> x = 1
>>> assert type(x) == IntType
>>> try:
...   assert type(x) == StringType, 'type error'
... except AssertionError, e:
...   print(e.message)
...
type error

注) この記事はPython2向けの内容となっています。

Python3ではtypesの代わりに

>>> type(1) == int
True
>>> type('') == str
True
>>> type([]) == list
True

のような感じで使えます。

ちなみに、intstrlistなどに使える値は

print([t.__name__ for t in __builtins__.__dict__.values() if isinstance(t, type)])

で一覧表示できます。

参考リンク

python – List of classinfo Types – Stack Overflow
https://stackoverflow.com/questions/51567356/list-of-classinfo-types