PR
Calendar
Keyword Search
Category
Free Space
>>> import urllib
>>> urlread = lambda url: urllib.urlopen(url).read()
>>> import chardet
>>> chardet.detect(urlread("http://google.cn/"))
{'encoding': 'GB2312', 'confidence': 0.99}
>>> import chardet
>>> chardet.detect("これはなに")
{'confidence': 0.5, 'encoding': 'windows-1252'}
>>> chardet.detect("蛇のとぐろを見る")
{'confidence': 0.21941992101760521, 'encoding': 'IBM866'}
>>> chardet.detect("東京のこれは何")
{'confidence': 0.5, 'encoding': 'windows-1252'}
>>> chardet.detect("文字列の判定をするのだ")
{'confidence': 0.5, 'encoding': 'windows-1252'}
句読点が含まれない短い文字列を判定させると、こける可能性があります。句読点を含む文字列なら大丈夫だと思いますが。
chardet.detect("。")
chardet.detect("、")
import pykf
pykf.guess("これはなに")
だとこけないので、短い文字列で日本語の文字列と分かっているなら pykf 等使った方が安全かもしれません。
>>> import encutils
>>> info = encutils.getEncodingInfo(url='http://cthedot.de/encutils/')
>>> info
<encutils.EncodingInfo object encoding='utf-8' mismatch=False at 0x12e3270>
>>> print info
utf-8
>>> print info.logtext
HTTP media_type: text/html
HTTP encoding: utf-8
HTML META media_type: text/html
HTML META encoding: utf-8
Encoding (probably): utf-8 (Mismatch: False)
>>> encutils.tryEncodings('これはなに')
'windows-1252'
>>> encutils.tryEncodings('蛇のとぐろを見る')
'IBM866'
>>> encutils.tryEncodings('東京のこれは何')
'windows-1252'
>>> encutils.tryEncodings('文字列の判定をするのだ')
'windows-1252'
>>> encutils.tryEncodings('。')
'SHIFT_JIS'
>>> encutils.tryEncodings('、')
'SHIFT_JIS'
try:
import chardet
encoding = chardet.detect(text)["encoding"]
import pykf
pykf.setdefault(pykf.SJIS) # デフォルトは SJIS にしてみる
pykf.setstrict(TRUE) # 厳しく判定
enc = {pykf.UNKNOWN:None, pykf.ASCII:'ASCII',
pykf.SJIS:'SHIFT-JIS', pykf.EUC:'EUC-JP',
pykf.JIS:'ISO-2022-JP', pykf.UTF8:'UTF-8',
pykf.UTF16:'utf-16', pykf.UTF16_BE:'utf-16_be',
pykf.ERROR:None}
def detect_encode(text):
g = pykf.guess(text)
return enc[g]
print detect_encode('これはなに')
print detect_encode('蛇のとぐろを見る')
print detect_encode('東京のこれは何')
print detect_encode('文字列の判定をするのだ')
try:
import pykf
pykf.setdefault(pykf.SJIS)
enc = {pykf.UNKNOWN:None, pykf.ASCII:'ASCII',
pykf.SJIS:'SHIFT-JIS', pykf.EUC:'EUC-JP',
pykf.JIS:'ISO-2022-JP', pykf.UTF8:'UTF-8',
pykf.UTF16:'utf-16', pykf.UTF16_BE:'utf-16_be',
pykf.ERROR:None}
encoding = enc[pykf.guess(text)]
janome を使った Python プログラムを pyi… 2024.04.08
Tkinter でも、見た目のよい GUI を作れる 2024.02.25
Chromecast を Python で制御する 2016.01.10