1
文件我有以下GraphML文件“mygraph.gml”,我想用一个简单的python脚本解析:如何循环GraphML与LXML
这代表了一个简单图2个节点“NODE0”,“节点1" 并把它们
<?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个节点,蟒蛇minidom命名太慢)
import lxml.etree as et
tree = et.parse('mygraph.gml')
root = tree.getroot()
graphml = {
"graph": "{http://graphml.graphdrawing.org/xmlns}graph",
"node": "{http://graphml.graphdrawing.org/xmlns}node",
"edge": "{http://graphml.graphdrawing.org/xmlns}edge",
"data": "{http://graphml.graphdrawing.org/xmlns}data",
"label": "{http://graphml.graphdrawing.org/xmlns}data[@key='label']",
"x": "{http://graphml.graphdrawing.org/xmlns}data[@key='x']",
"y": "{http://graphml.graphdrawing.org/xmlns}data[@key='y']",
"size": "{http://graphml.graphdrawing.org/xmlns}data[@key='size']",
"r": "{http://graphml.graphdrawing.org/xmlns}data[@key='r']",
"g": "{http://graphml.graphdrawing.org/xmlns}data[@key='g']",
"b": "{http://graphml.graphdrawing.org/xmlns}data[@key='b']",
"weight": "{http://graphml.graphdrawing.org/xmlns}data[@key='weight']",
"edgeid": "{http://graphml.graphdrawing.org/xmlns}data[@key='edgeid']"
}
graph = tree.find(graphml.get("graph"))
nodes = graph.findall(graphml.get("node"))
edges = graph.findall(graphml.get("edge"))
这个脚本得到正确的节点和边缘,使我可以在他们简单地重复
for n in nodes:
print n.attrib
上边缘
或类似:
for e in edges:
print (e.attrib['source'], e.attrib['target'])
但我无法真正理解如何获得边或节点的“数据”标签以打印边缘权重和节点标签“名称”。
这并没有为我工作:
weights = graph.findall(graphml.get("weight"))
最后的名单始终是空的。为什么?我错过了一些东西,但不明白是什么。
谢谢!这绝对是我寻找的解决方案! 再次感谢,现在我了解了树的结构以及如何迭代它。 – linello 2012-04-18 10:09:13