在python中使用networkx处理graphml文件

geo*_*kos 5 python xml networkx

我需要处理由 yEd 图创建的 graphml (XML) 文件,以便获取该图的节点和边属性。我需要使用 networkX 库来做到这一点。我是 Python 新手,从未使用过 networkX 库,因此我们将不胜感激。

gau*_*den 8

这应该让你开始...

在 yEd 中创建图形并使用 GraphML 格式文件 > 另存为...。比如说,您将其保存到文件“test.graphml”。

导航到该目录并运行 Python:

>>> import networkx as nx
>>> import matplotlib.pyplot as plt
>>> G = nx.read_graphml('test.graphml')
>>> nx.draw(G)
>>> plt.show()
>>> 
Run Code Online (Sandbox Code Playgroud)

此外,如果您想读取和处理节点的属性,您可以迭代它们,从它们中提取数据,如下所示:

for node in G.nodes(data=True):
    print node
Run Code Online (Sandbox Code Playgroud)

这将导致类似这样的结果(我在 yEd 中创建了一个随机图来测试这一点):

('n8', {'y': '178.1328125', 'x': '268.0', 'label': '8'})
('n9', {'y': '158.1328125', 'x': '0.0', 'label': '9'})
('n0', {'y': '243.1328125', 'x': '160.0', 'label': '0'})
('n1', {'y': '303.1328125', 'x': '78.0', 'label': '1'})
('n2', {'y': '82.1328125', 'x': '221.0', 'label': '2'})
('n3', {'y': '18.1328125', 'x': '114.0', 'label': '3'})
('n4', {'y': '151.1328125', 'x': '170.0', 'label': '4'})
('n5', {'y': '122.1328125', 'x': '85.0', 'label': '5'})
('n6', {'y': '344.1328125', 'x': '231.0', 'label': '6'})
('n7', {'y': '55.1328125', 'x': '290.0', 'label': '7'})
Run Code Online (Sandbox Code Playgroud)

作为最后一个示例,如果想要访问节点的 x 坐标n5,则:

>>> print G['n5']['x']
Run Code Online (Sandbox Code Playgroud)

会给你85.0。