python networkx教程,在python中使用networkx处理graphml文件

I need to process a graphml (XML) file created by a yEd graph in order to get the node and edges attributes of that graph. I need to do that using the networkX library. I'm new at Python and I have never used the networkX library so any help would be appreciated.

解决方案

This should get you started...

In yEd create the graph and File > Save As... using the GraphML format. Say, you save it to file 'test.graphml'.

Navigate to that directory and run Python:

>>> import networkx as nx

>>> import matplotlib.pyplot as plt

>>> G = nx.read_graphml('test.graphml')

>>> nx.draw(G)

>>> plt.show()

>>>

Furthermore, if you want to read and process the attributes of the nodes, you can iterate through them, extracting the data from them like this:

for node in G.nodes(data=True):

print node

This will result in something like this (I created a random graph in yEd to test this):

('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'})

As a final example, if one wants to access the x coordinate of node n5, then:

>>> print G['n5']['x']

will give you 85.0.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值