python点滴

2009年3月11日 00:57

1.文字编码识别

dev-python/chardet 是可识别文字编码类型的python库

$cat encoding_detector.py

#!/usr/bin/env python
# vim: set fileencoding=utf-8:
import chardet
import sys

print chardet.detect(open(sys.argv[1], 'r').read())

$./encoding_detector.py weird_coding_file

{'confidence': 0.98999999999999999, 'encoding': 'GB2312'}
 

2.文字编码转换

将gb2312编码的文件转换为utf8

$iconv -f gb2312 -t utf8 weird_coding_file > utf8_coding_file

但如果文件中有非gb2312编码的字符,就会使转换中止。

这时可以用python提供的库。

$cat gb2312toutf8.py

#!/usr/bin/env python
# vim: set fileencoding=utf-8:
import sys

fp1 = open(sys.argv[1], 'r')
fp2 = open(sys.argv[2], 'w')
fp2.write(fp1.read().decode('GB2312', 'ignore').encode('UTF-8', 'ignore'))

$./gb2312toutf8.py input output

上面的ignore参数,可以忽略解码过程中的异常。