Python判断字符集

时间:2023-03-09 18:25:41
Python判断字符集

Python利用第三方库chardet可以判断字符集。

https://chardet.readthedocs.io

>>> import urllib
>>> rawdata = urllib.urlopen('http://yahoo.co.jp/').read()
>>> import chardet
>>> chardet.detect(rawdata)
{'encoding': 'EUC-JP', 'confidence': 0.99}

  

判断文件的字符集

 detector = UniversalDetector()
for filename in glob.glob('*.txt'):
print(filename.ljust(60), )
detector.reset()
for line in open(filename, 'rb'):
detector.feed(line)
if detector.done: break
detector.close()
print(detector.result)

  显示结果:

Python判断字符集