Python字符编码

2019-10-10  本文已影响0人  shuhanghang

一.常见编码

ASCII:使用单个字节表示字符,最高位为0,最多能表示128个字符(数字+字母+特殊符号)
GB2312:使用两个字节表示字符,兼容ASCII编码,能表示中文
Unicode:通常用两个字节表示字符,表示多种语言
UTF-8:针对 Unicode的一种可变长度字符编码,用一到四个字节表示字符,兼容ASCII编码,能表示多种语言

二.python2编码

1.字符串类型
str:一般都为str类型,类似bytes,该类型的字符串decode()后为unicode类型
unicode:使用'u'声明或使用unicode()函数创建字符串,该类型的字符串encode()后得到str类型

2.类型转换关系图

3.查看python2默认编码

>>> import sys
>>> reload(sys)
<module 'sys' (built-in)>
>>> sys.getdefaultencoding()
'ascii'

sys.setdefaultencoding()设置默认编码

4.检测创建字符串编码

>>> import chardet
>>> a='a'
>>> type(a)
<type 'str'>
>>> chardet.detect(a)
{'confidence': 1.0, 'language': '', 'encoding': 'ascii'}
>>> a='测试'
>>> chardet.detect(a)
{'confidence': 0.7525, 'language': '', 'encoding': 'utf-8'}

默认的当字符串为数字字母或特殊符号为ASCII编码,包含中文为UTF-8编码

三.python3默认编码

1.字符串类型
str:类似python2 unicode类型,该类型的字符串encode()后得到bytes类型
bytes:类似pytho2 str类型,该类型的字符串decode()后为str类型
bytearray:可变的整数序列

2.查看python3默认编码

>>> import sys
>>> sys.getdefaultencoding()
'utf-8'

sys.setdefaultencoding()设置默认编码

四.实例

python3爬虫requests.get解析到的HTML是似Unicode类型的字符串

>>> import requests
>>> url = r'https://s.search.bilibili.com/cate/search?callback=jqueryCallback_bili_8033182213391138&main_ver=v3&search_type=video&view_type=hot_rank&order=click&copy_right=-1&cate_id=163&page=1&pagesize=100&jsonp=jsonp&time_from=20191001&time_to=20191031&_=1570496516751'

>>> res_html=requests.get(url).content    #content属性返回的二进制数据
>>> type(res_html)
'<class 'bytes'>'
>>> print(res_html)
b'tag:\\u7bee\\u7403,\\u4f53\\u80b2'    #截取片段
>>> print(res_html.decode('unicode-escape'))    #将类型为bytes含unicode编码的字符串解码为中文
'tag:篮球,体育'

>>> res_html=requests.get(url).text    #text属性返回的是Unicode类型数据
'<class 'str'>'
>>> print(res_html)
'tag:\\u7bee\\u7403,\\u4f53\\u80b2'     #截取片段
>>> print(res_html.encode().decode('unicode-escape'))    #将类型转换成bytes再解码unicode为中文
'tag:篮球,体育'
上一篇 下一篇

猜你喜欢

热点阅读