python_判断字符串编码的方法

1. 安装chardet

    在命令行中,进入Python27\Scripts目录,输入以下的命令:easy_install chardet

2. 操作

import chardet
f = open('file','r')
fencoding=chardet.detect(f.read())
print fencoding

fencoding输出格式 {'confidence': 0.96630842899499614, 'encoding': 'GB2312'} ,只能判断是否为某种编码的概率。比较准确的结果了。输入参数为str类型。

备注:

  • str利用decode方法根据str的编码将其解码为unicode字符串类型
  • str利用encode根据特定的编码将unicode字符串类型转换为特定的编码
posted @ 2017-01-13 15:06  坏脾气  阅读(26499)  评论(0编辑  收藏  举报