编码、转码和编码格式

1.字符串的编码:python3中字符串类型str就是以Unicode编码格式编码。编码是一种用一种特定的方式对抽象字符(Unicode)转换为二进制形式(bytes)进行表示,也就是python3中的encode。解码就是对用特定方式表示的二进制数据用特定的方式转化为Unicode,也就是decode。如果你对str类型字符进行decode会报错,同理,对bytes类型进行encode也会报错。编码和解码必须要使用同一种编码格式进行处理否则就会报错!

s='你好'
print(s)#输出结果:你好
print(type(s))#输出结果:<class 'str'>
s=s.encode('UTF-8')
print(s)#输出结果:b'\xe4\xbd\xa0\xe5\xa5\xbd'
print(type(s))#输出结果:<class 'bytes'>
s=s.decode('UTF-8')
print(s)#输出结果:你好
print(type(s))#输出结果:<class 'str'>

2.文件的编码:如果以‘w’模式写入,则要求写入的内容必须是str类型;如果以‘wb’形式写入,则要求写入的内容必须是bytes类型。有的人会问,我在系统里面用文本编辑器打开以bytes形式写入的2.txt文件,发现里面显示的是‘你好’,而不是‘b'\xe4\xbd\xa0\xe5\xa5\xbd'’,因为文本文档打开2.txt时,又会对它进行decode,然后才给你看到。

s1 = '你好'#如果是以‘w’的方式写入,写入前一定要进行encoding,否则会报错 
with open('F:\\1.txt','w',encoding='utf-8') as f1:
    f1.write(s1)
s2 = s1.encode("utf-8")#转换为bytes的形式
#这时候写入方式一定要是‘wb’,且一定不能加encoding参数
with open('F:\\2.txt','wb') as f2:
    f2.write(s2)

3.网页的编码:网页编码和文件编码方法差不多,如下urlopen下载下来的网页read()且用decoding(‘utf-8’)解码,那就必须以‘w’的方式写入文件。如果只是read()而不用encoding(‘utf-8’)进行编码,一定要以‘wb’方式写入。

以‘w’方式写入时:

response= urlopen('http://blog.csdn.net/gs_zhaoyang/article/details/13768925 ')
#此处以UTF-8方式进行解码,解码后的数据以unicode的方式存储在html中
html = response.read().decode('UTF-8')
print(type(html))#输出结果:<class 'str'>
#这时写入方式一定要加encoding,以encoding
# 即UTF-8的方式对二进制数据进行编码才能写入
with open('F:\DownloadAppData\html.txt',"w" , encoding='UTF-8') as f:
    f.write(html)

以‘wb’方式写入:

response= urlopen('http://blog.csdn.net/gs_zhaoyang/article/details/13768925')
html = response.read()#此处不需要进行解码,下载下来
print(type(html))#输出结果:<class 'bytes'>
with open('F:\DownloadAppData\html.txt',"wb" ) as f:
    f.write(html)

编码格式:

1.为了处理英文字符,产生了ASCII码。 
2.为了处理中文字符,产生了GB2312。 
3.为了处理各国字符,产生了Unicode。 
4.为了提高Unicode存储和传输性能,产生了UTF-8,它是Unicode的一种实现形式。**

猜你喜欢

转载自blog.csdn.net/runs_after_the_wind/article/details/82501476
今日推荐