Pythonで端末のエンコーディング取得はgetpreferredencoding
でできます。
>>> import sys
>>> locale.getpreferredencoding()
'cp932'
「あいうえお」と表示するスクリプト(sample.py)
# -*- coding: UTF-8 -*-
s = u'あいうえお'
print s
コマンドプロンプトから
> python.exe sample.py
あいうえお
出力をファイルにリダイレクト
> python.exe sample.py > sample.txt
Traceback (most recent call last):
File "a.py", line 3, in <module>
print s
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-4: ordinal not in range(128)
エンコーディングを取得するように修正
# -*- coding: UTF-8 -*-
import locale
encoding = locale.getpreferredencoding()
s = u'あいうえお'
print s.encode(encoding)
問題なく表示できます。
> python.exe sample.py
あいうえお
関連記事
Pythonでnkf
Pythonで文字コードが不明な文字列(例えばインターネット上のHTMLは文字コードが間違っている場合があります)はnkfを使うと簡単に取り扱うことができるみたいです。
# emerge -pv app-i18n/nkf
These are the packages that would be merged, in order:
Calculating dependencies... ...
python-chardet
python-chardetを使った文字コード推定
使い方
>>> import chardet
>>> s = 'こんにちは'
>>> chardet.detect(s)
{'confidence': 0.9690625, 'encoding': 'utf-8'}
>>> s.decode(chardet.detect(s)['encoding'])
u'\u3053\u3...