无法在networkx中以graphml格式写入带有属性的图
我正在尝试把我的有向图导出为graphml格式,使用的是networkx库。下面是我在networkx中的图的代码,以及我遇到的错误:
h = nx.path_graph(5)
G.add_nodes_from(h)
G.add_edges_from(h.edges()
G[0]['name']="panama"
G[1]['name']="costa rica"
G[2]['name']="Argentina"
G[3]['name']="Brazil"
G[4]['name']="Coloumbia"
G[1][2]['connection']='road'
nx.write_graphml(G,"te.graphml")
错误信息:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 2, in write_graphml
File "/usr/local/lib/python2.7/dist-packages/networkx/utils/decorators.py", line 220, in _open_file
result = func(*new_args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/networkx/readwrite/graphml.py", line 82, in write_graphml
writer.add_graph_element(G)
File "/usr/local/lib/python2.7/dist-packages/networkx/readwrite/graphml.py", line 351, in add_graph_element
self.add_edges(G,graph_element)
File "/usr/local/lib/python2.7/dist-packages/networkx/readwrite/graphml.py", line 325, in add_edges
self.add_attributes("edge", edge_element, data, default)
File "/usr/local/lib/python2.7/dist-packages/networkx/readwrite/graphml.py", line 297, in add_attributes
for k,v in data.items():
AttributeError: 'str' object has no attribute 'items'
1 个回答
2
你可以对NetworkX内部的数据结构进行赋值,但在这种情况下,你的赋值方式不对(这会导致数据结构出问题)。
你有
h = nx.path_graph(5)
G.add_nodes_from(h)
G.add_edges_from(h.edges()
G[0]['name']="panama" <--- this corrupts the adjacency data structure
使用
G.node[0]['name']='panama'
来给节点赋值。