我有下面的图形文件'我的图形.gml'我想用一个简单的python脚本解析:
这表示一个简单的图,其中有两个节点“node0”、“node1”以及它们之间的一条边
<?xml version="1.0" encoding="UTF-8"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns
http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
<key id="name" for="node" attr.name="name" attr.type="string"/>
<key id="weight" for="edge" attr.name="weight" attr.type="double"/>
<graph id="G" edgedefault="directed">
<node id="n0">
<data key="name">node1</data>
</node>
<node id="n1">
<data key="name">node2</data>
</node>
<edge source="n1" target="n0">
<data key="weight">1</data>
</edge>
</graph>
</graphml>
这表示一个有两个节点n0和n1的图,它们之间有一个权重为1的边。 我想用python解析这个结构。在
我在lxml的帮助下编写了一个脚本(我需要使用它,因为数据集比这个简单的例子要大得多,超过10^5个节点,python minidom太慢了)
^{pr2}$这个脚本正确地获取了节点和边,所以我可以简单地迭代它们
for n in nodes:
print n.attrib
或类似的边缘:
for e in edges:
print (e.attrib['source'], e.attrib['target'])
但我真的不明白如何获取边或节点的“data”标记以打印边权重和节点标记“name”。在
这不适合我:
weights = graph.findall(graphml.get("weight"))
最后一个列表总是空的。为什么?我错过了一些东西,但不明白是什么。在
不能一次完成,但对于找到的每个节点,可以使用数据的键/值构建dict:
结果是:
^{pr2}$相关问题 更多 >
编程相关推荐