Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/322.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/iphone/42.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在处理urllib响应而不是chr(int(x))时将字节转换为字符串更具pythonic_Python_Character Encoding_Urllib - Fatal编程技术网

在处理urllib响应而不是chr(int(x))时将字节转换为字符串更具pythonic

在处理urllib响应而不是chr(int(x))时将字节转换为字符串更具pythonic,python,character-encoding,urllib,Python,Character Encoding,Urllib,我很晚才转换成Python 3。我正在尝试使用urllib处理RESTAPI的蛋白质序列输出 在传统python中,我可以使用: self.seq_fileobj = urllib2.urlopen("http://www.uniprot.org/uniprot/{}.fasta".format(uniprot_id)) self.seq_header = self.seq_fileobj.next() print "Read in sequence information for {}.".f

我很晚才转换成Python 3。我正在尝试使用urllib处理RESTAPI的蛋白质序列输出

在传统python中,我可以使用:

self.seq_fileobj = urllib2.urlopen("http://www.uniprot.org/uniprot/{}.fasta".format(uniprot_id))
self.seq_header = self.seq_fileobj.next()
print "Read in sequence information for {}.".format(self.seq_header[:-1])
self.sequence = [achar for a_line in self.seq_fileobj for achar in a_line if achar != "\n"]
print("Sequence:{}\n".format("".join(self.sequence)))
对于python 3中的同一段代码,我使用:

context = ssl._create_unverified_context()
self.seq_fileobj = urllib.request.urlopen("https://www.uniprot.org/uniprot/{}.fasta".format(uniprot_id),context=context)
self.seq_header = next(self.seq_fileobj)
print("Read in sequence information for {}.".format(self.seq_header.rstrip()))
self.b_sequence = [str(achar).encode('utf-8') for a_line in self.seq_fileobj for achar in a_line]
self.sequence = [chr(int(x)) for x in self.b_sequence]
我已经阅读了一些关于字符串编码和解码的内容,以修改我对python 3的列表理解:

self.b_sequence = [str(achar).encode('utf-8') for a_line in self.seq_fileobj for achar in a_line]
self.sequence = [chr(int(x)) for x in self.b_sequence]

虽然我的代码正在工作,但这是实现这个结果的最佳方法吗?我从用utf-8编码的ascii字符字节数组到它们的结果字符串?。chr(int(x))位对我来说似乎不是pythonic,我担心我可能遗漏了一些东西。

您不需要将字节转换为字符对字符的字符串。由于要去除换行符,因此可以将整个文件作为字节读取,使用
decode
方法将字节转换为字符串(使用时默认为
utf-8
编码),然后使用
str.replace
方法删除换行符:

self.sequence = list(self.seq_fileobj.read().decode().replace('\n', ''))

谢谢。这是如此的干净,我现在明白了解码基本上是在列表理解中完成的。字符串本身是一个序列,可以像
列表一样访问。除非内容需要修改,否则无需将其转换为
列表。