无法在networkx中以graphml格式编写带有属性的图形

时间:2014-07-10 16:51:49

标签: python networkx graphml

我正在尝试将有向图导出为networkx中的graphml格式。这是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 个答案:

答案 0 :(得分: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'

将数据分配给节点。