您的位置:首页 > 编程语言 > Python开发

python编码问题之\"encode\"&\"decode\"

2017-03-26 11:27 387 查看
pythonencodedecode编码

decode的作用是将其他编码的字符串转换成unicode编码,如str1.decode(‘gb2312’),表示将gb2312编码的字符串str1转换成unicode编码。

encode的作用是将unicode编码转换成其他编码的字符串,如str2.encode(‘gb2312’),表示将unicode编码的字符串str2转换成gb2312编码。

当我们想获取网页源代码,并且希望能够以html后缀或者其他格式保存文件的时候,如果不进行编码,那么保存得到的文件在遇到中文时就会出现异常,不便于我们对数据的处理。

  • requests

首先说一下使用requests请求得到源代码的处理办法。
经过我无数次的实践,发现通过get请求得到的源代码都是“byte”类型,所以每当想都过write写入到文件中时总是会报错。如下:

  1. #coding=utf-8 
  2. import requests 
  3.  
  4. r = requests.get('http://www.baidu.com') 
  5.  
  6. print(type(r.text)) 
  7. with open('baidu.html','w') as f: 
  8.     f.write(r.text) 

输出结果

  1. >>> 
  2. <class 'str'> 
  3. Traceback (most recent call last): 
  4.   File "C:\Users\14356_000\Desktop\test.py", line 8, in <module> 
  5.     f.write(r.text) 
  6. UnicodeEncodeError: 'gbk' codec can't encode character '\xbb' in position 25364: illegal multibyte sequence 

解决办法:示例代码如下

  1.  
  2. import requests 
  3. import chardet 
  4.  
  5. r = requests.get('http://www.baidu.com') 
  6. content = r.text 
  7. print(type(content)) 
  8. print(chardet.detect(content.encode('utf-8'))) 
  9. with open('baidu.html','w',encoding='utf-8') as f: 
  10.     f.write(content.encode('utf-8').decode('utf-8')) 

注意chardet是用来查看文字编码类型的,之前想使用下面代码直接查看content的编码类型,但是报错。

  1. ... 
  2. ... 
  3. print(chardet.detect(content)) 
  4.  
  5. >>> 
  6. Traceback (most recent call last): 
  7.   File "C:\Users\14356_000\Desktop\test.py", line 8, in <module> 
  8.     print(chardet.detect(content)) 
  9.   File "C:\Python35\lib\site-packages\chardet\__init__.py", line 25, in detect 
  10.     raise ValueError('Expected a bytes object, not a unicode object') 
  11. ValueError: Expected a bytes object, not a unicode object 

因此需要先通过encode,将content的编码格式转化为utf-8才能查看。。这里还没弄清楚为什么Expected a bytes object, not a unicode object,先放着。
下面说说写入操作。写入操作之前需要制定encoding的方式为utf-8,另外f.write()时还得先把content的编码格式设置成utf-8,然后再通过decode解码,将utf-8格式解码成Unicode格式,即python内置的编码格式,这样就能正常写入了,而且中文正常显示!!!
下面是最上面代码的输出结果。

  1. >>> 
  2. <class 'str'> 
  3. {'encoding': 'utf-8', 'confidence': 0.99} 
  4. [Finished in 2.3s] 
  • urllib

先写到这~~~

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐