字符编码转换
Python字符编码转换:
一、Python3中的编码转换(python3中默认就是unicode编码)
#!/usr/bin/env python #-*- coding:utf-8 -*- #author huan tim = ‘天‘ #转为UTF-8编码 print(tim.encode(‘UTF-8‘)) #转为GBK编码 print(tim.encode(‘GBK‘)) #转为ASCII编码(报错为什么?因为ASCII码表中没有‘天’这个字符集~~) print(tim.encode(‘ASCII‘))
二、Python2.x中的编码转换
因为在python2.X中默认是ASCII编码,你在文件中指定编码为UTF-8,但是UTF-8如果你想转GBK的话是不能直接转的,需要Unicode做一个转接站点。
#!/usr/bin/env python #-*- coding:utf-8 -*- #author huan import chardet tim = ‘你好‘ print chardet.detect(tim) #先解码为Unicode编码,然后在从Unicode编码为GBK new_tim = tim.decode(‘UTF-8‘).encode(‘GBK‘) print chardet.detect(new_tim) #结果 ‘‘‘ {‘confidence‘: 0.75249999999999995, ‘encoding‘: ‘utf-8‘} {‘confidence‘: 0.35982121203616341, ‘encoding‘: ‘TIS-620‘} ‘‘‘
相关推荐
liusarazhang 2020-06-28
89411051 2020-06-14
FORYAOSHUYUN 2020-06-11
88540591 2020-06-01
81214051 2020-04-25
84590091 2020-04-22
Airuio 2020-01-28
amberom 2019-12-24
typhoonpython 2019-11-19
JakobHu 2019-11-09
80467305 2019-11-04
butterflyfly00 2019-11-04
wklken的笔记 2019-10-27
88384957 2019-10-26
zbcaicai 2019-10-23
yiyilanmei 2020-08-03
mjshldcsd 2020-06-14
王艺强 2020-06-12
LUOPING0 2020-05-18