UnicodeEncodeError : 'latin-1'编解码器无法在位置 8 中编码字符 '\u01e2':序号不在范围 (256) 中。如何解决?



我必须通过MobiDB提供的代码访问数据库,才能对蛋白质进行紊乱预测。

import urllib2
import json
# Define request
acceptHeader = 'My_File_TrEMBL.txt' # text/csv and text/plain supported
request = urllib2.Request("https://mobidb.org/ws/P04050/uniprot", headers={"Accept" : acceptHeader})
# Send request
response = urllib2.urlopen(request)
# Parse JSON response di Python dict
data = json.load(response)
# handle data
print(data)

由于我没有使用Python 2.6,我更改了脚本如下:

import urllib.request
import json
# Define request
acceptHeader ='My_File_TrEMBL.txt' 
# text/csv and text/plain supported
request = urllib.request.Request("https://mobidb.org/ws/P04050/uniprot", headers={"Accept" : 
acceptHeader})
# Send request
response = urllib.request.urlopen(request)
# Parse JSON response di Python dict
data = json.load(response)
# handle data
print(data)

所以我使用的不是urlib2,而是urlib.request。当变量请求被传递给urlib.rerequest.urlopen时,问题就出现了,它会给我返回这个实例:

"'latin-1'编解码器无法对位置8中的字符'\u01e2'进行编码:序号不在范围(256(内";

我知道这与ASCII代码有关,但由于我是Python的新手,而且我很渴望在截止日期前完成工作,我希望你能给我任何帮助。倾斜

使用utf-8编码解码字节内容,并使用json.loads读取内容

response = urllib.request.urlopen(request)
#get the content and decode it using utf-8
respcontent = response.read().decode('utf-8')
data = json.loads(respcontent)
print(data)

最新更新