从Python2转换为Python3:TypeError:需要类似字节的对象
我得到了以下Python 2x代码。我通过将从Python2转换为Python3:TypeError:需要类似字节的对象,python,urllib2,urllib,Python,Urllib2,Urllib,我得到了以下Python 2x代码。我通过将import urlib2更改为从urlib.request import urlopen将其转换为Python 3x。我去掉了urllib2引用并运行了这个程序。已检索url末尾的文档,但程序在指定行失败,引发错误 TypeError: a bytes-like object is required, not 'str' 文档如下所示:b'9306112 9210128 9202065\r\n9306114 9204065 9301122\r\n9
import urlib2
更改为从urlib.request import urlopen
将其转换为Python 3x。我去掉了urllib2引用并运行了这个程序。已检索url末尾的文档,但程序在指定行失败,引发错误
TypeError: a bytes-like object is required, not 'str'
文档如下所示:b'9306112 9210128 9202065\r\n9306114 9204065 9301122\r\n9306115\r\n9306116\r\n9306117\r\n9306118\r\n9306119
我试着在那一行和上面的一行中使用返回值(例如,转换为字节,在不同的值上进行分割),但没有任何效果。对发生的事情有什么想法吗
import urllib2
CITATION_URL = "http://storage.googleapis.com/codeskulptor-alg/alg_phys-cite.txt"
def load_graph(graph_url):
"""
Function that loads a graph given the URL
for a text representation of the graph
Returns a dictionary that models a graph
"""
graph_file = urllib2.urlopen(graph_url)
graph_text = graph_file.read()
graph_lines = graph_text.split('\n') <--- The Problem
graph_lines = graph_lines[ : -1]
print "Loaded graph with", len(graph_lines), "nodes"
answer_graph = {}
for line in graph_lines:
neighbors = line.split(' ')
node = int(neighbors[0])
answer_graph[node] = set([])
for neighbor in neighbors[1 : -1]:
answer_graph[node].add(int(neighbor))
return answer_graph
citation_graph = load_graph(CITATION_URL)
print(citation_graph)
导入urllib2
引文URL=”http://storage.googleapis.com/codeskulptor-alg/alg_phys-cite.txt"
def加载图(图url):
"""
函数,用于加载给定URL的图形
用于图形的文本表示
返回为图形建模的字典
"""
graph_file=urllib2.urlopen(graph_url)
graph\u text=graph\u file.read()
graph\u lines=graph\u text.split('\n')要将bytes
对象视为字符串,需要先对其进行解码。例如:
graph_text = graph_file.read().decode("utf-8")
如果编码是UTF-8。这应该允许您将其视为字符串,而不是字节序列。要将字节
对象视为字符串,您需要首先对其进行解码。例如:
graph_text = graph_file.read().decode("utf-8")
如果编码是UTF-8。这应该允许您将其视为字符串,而不是字节序列。您只能将喜欢与喜欢分割-如果您想使用\n
分割,同时仍将图形文本
保留为字节
,请将分割定义为字节
序列:
graph_lines = graph_text.split(b'\n')
否则,如果您知道您的graph\u text
数据编码所使用的编解码器,请首先使用graph\u text.decode(“”)将其解码为str
然后继续将其视为str
您只能将喜欢与喜欢进行拆分-如果您想使用\n
进行拆分,同时仍将图形文本
保留为字节
,请将拆分也定义为字节
序列:
graph_lines = graph_text.split(b'\n')
否则,如果您知道您的graph\u text
数据编码所使用的编解码器,请首先使用graph\u text将其解码为str
。解码(“”
),然后继续将其视为python3中的str
,在读取字节时必须进行解码。graph_text.decode(“utf-8”)要在python3中执行字符串操作,您必须在读取字节时进行解码。图形\文本解码(“utf-8”)以执行字符串操作