字符编码 - python使用split(‘中文字符’)出错
PHP中文网
PHP中文网 2017-04-18 09:04:39
0
4
1020

根据网页所给的字符编码将其字节数据decode('gb2312')
用的是scrapy,从给出的url获取body

def parse(self, response):
    body = response.body.decode('gb2312')
    print(body)    
    学分:1.5 # body就是这样之类的,中间的冒号是中文的冒号
    # 想弄成的效果就是['学分','1.5']
    body = body.split(':') # 就这样使用中文的冒号符来分割,但是出错
SyntaxError: (unicode error) 'utf-8' codec can't decode byte 0xa3 in position 0: invalid start byte

请问怎么解决?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(4)
大家讲道理
# 我尝试了这样做
print(body.encode('gb2312'))
print(body.encode('utf-8'))
输出如下:
b'\xb3\xd0\xb5\xa3\xb5\xa5\xce\xbb\xa3\xba\xd5\xfe\xb7\xa8\xd1\xa7\xd4\xba'
b'\xe6\x89\xbf\xe6\x8b\x85\xe5\x8d\x95\xe4\xbd\x8d\xef\xbc\x9a\xe6\x94\xbf\xe6\xb3\x95\xe5\xad\xa6\xe9\x99\xa2'
#再令两个结果分别为gb2312和utf8
>>> gb2312.decode('utf-8')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 0: invalid start byte

Look at the above error again, it is byte 0xa3
So I tried it several times on the terminal and found that the colon gb2312 encode

>>> b'\xa3\xba'.decode('gb2312')
':'

So it should be that python uses the default utf-8 to decode the body of gb2312, so one way I can think of is to modify the default encoding value, which is the statement in the first line: # -*- coding: gb2312 -*-
Then the operation was successful. Is there anything else? method?

迷茫

Python3

伊谢尔伦

After decoding, the body should be unicode encoded, use the following method:

body = body.split(u':')
Ty80

Another encoding issue, you can refer to: Character Encoding for Human-Computer Interaction and Defeating Python Character Encoding in Five Minutes.

#! /usr/bin/env python
# -*- coding: utf-8 -*-

# 模仿你从网页获得的数据
data = "学分:1.5".decode("utf-8").encode('gb2312')
# data = u"学分:1.5".encode('gb2312')
print type(data)

body = data.decode('gb2312')
print type(body)    # unicode 类型

# 两种解决方案
print body.split(u':')  # unicode 对应 unicode
print body.encode("utf-8").split(":")  # utf-8 对应 utf-8
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!