LoginSignup
1
0

More than 5 years have passed since last update.

pythonのchardetでWindows-1254とか誤検出するときはuniversaldetectorではなく素のdetectを使う

Posted at

なにがおきた

NetscapeNavigator4.xの頃から長年育て上げてきたサイトのhtmlやらcssやらjsやらを舐めたおすプログラムを書いてたんだが、Shift_JISのファイルのオープンに失敗することがある。

なにがおきてる

chardetのuniversaldetectorを使ってたんだが、文字コードの検出に失敗している模様。

なにをした

スピードとか必要ないローカル用のプログラムなのでuniversaldetectorじゃなくてchardet.detectを使うようにした。

detect.py
import chardet
from chardet.universaldetector import UniversalDetector

with open('style.css', mode='rb') as f:
    detector = UniversalDetector()
    for binary in f:
        detector.feed(binary)
        if detector.done:
            break
    detector.close()
    enc1 = detector.result

with open('style.css', mode='rb') as f:
    for binary in f:
        enc2 = chardet.detect(binary)

print(enc1)
# {'confidence': 0.5002330097559203, 'encoding': 'Windows-1254', 'language': 'Turkish'}

print(enc2)
# {'confidence': 1.0, 'encoding': 'ascii', 'language': ''}

ちなみに「style.css」はShift_JISのファイルなんで、厳密には誤検出してるんやがとりあえずこれで実害無くなったので。

結論

Perlでかきたい。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0