从 pickle 文件上传图表时出现问题
Problem uploading a graph from a pickle file
作为程序的一部分,我必须从 pickle 文件中读取图表,然后 return 将其作为图表读取。我必须说我正在使用 OSMnx 和 networkx 这样做。
我已经有了这个 pickle 文件,其中包含从 OSMnx 下载的图表。但是当我调用函数时它会引发错误。
代码:
import networkx
import osmnx as ox
import requests
import matplotlib.cm as cm
import matplotlib.colors as colors
import pickle
ox.config(use_cache=True, log_console=True)
ox.__version__
def load_graph(filename):
"""Uploads a graph from a pickle file and it returns it"""
infile = open(filename, 'rb')
G = pickle.load(infile)
infile.close()
return G
def main():
ox.plot_graph(load_graph("graph1.pickle"))
main()
错误:
AttributeError: 'str' object has no attribute 'nodes'
我该怎么办?
您没有提供可重现的代码片段(例如,我不知道您是如何生成 graph1.pickle
文件的或它包含的内容),但是这个类似的代码片段可以很好地处理 pickling:
import osmnx as ox
import pickle
ox.config(use_cache=True, log_console=True)
G = ox.graph_from_place('Piedmont, CA, USA', network_type='drive')
pickle.dump(G, open('graph.pickle', 'wb'))
G2 = pickle.load(open('graph.pickle', 'rb'))
fig, ax = ox.plot_graph(G2)
顺便说一句:作为图形序列化酸洗的替代方法,您还可以使用 OSMnx 的内置 save_graphml
和 load_graphml
functions.
作为程序的一部分,我必须从 pickle 文件中读取图表,然后 return 将其作为图表读取。我必须说我正在使用 OSMnx 和 networkx 这样做。
我已经有了这个 pickle 文件,其中包含从 OSMnx 下载的图表。但是当我调用函数时它会引发错误。
代码:
import networkx
import osmnx as ox
import requests
import matplotlib.cm as cm
import matplotlib.colors as colors
import pickle
ox.config(use_cache=True, log_console=True)
ox.__version__
def load_graph(filename):
"""Uploads a graph from a pickle file and it returns it"""
infile = open(filename, 'rb')
G = pickle.load(infile)
infile.close()
return G
def main():
ox.plot_graph(load_graph("graph1.pickle"))
main()
错误:
AttributeError: 'str' object has no attribute 'nodes'
我该怎么办?
您没有提供可重现的代码片段(例如,我不知道您是如何生成 graph1.pickle
文件的或它包含的内容),但是这个类似的代码片段可以很好地处理 pickling:
import osmnx as ox
import pickle
ox.config(use_cache=True, log_console=True)
G = ox.graph_from_place('Piedmont, CA, USA', network_type='drive')
pickle.dump(G, open('graph.pickle', 'wb'))
G2 = pickle.load(open('graph.pickle', 'rb'))
fig, ax = ox.plot_graph(G2)
顺便说一句:作为图形序列化酸洗的替代方法,您还可以使用 OSMnx 的内置 save_graphml
和 load_graphml
functions.