使用networkx(python)读取GML文件,不带节点标签

时间:2016-08-29 07:39:42

标签: python networkx graph-modelling-language

我有一个很长的GML文件(图形建模语言),我试图用Python中的Networkx阅读。 在GML文件中,节点没有标签,如下所示:

graph [
  node [
    id 1
  ]
  node [
    id 2
  ]
  edge [
    source 2
    target 1
    ]
  ]

我在阅读文件时遇到错误: G = nx.read_gml('simple_graph.gml')

---------------------------------------------------------------------------
NetworkXError                             Traceback (most recent call last)
<ipython-input-39-b1b319a08668> in <module>()
----> 1 G = nx.read_gml('simple_graph.gml')

<decorator-gen-319> in read_gml(path, label, destringizer)

/usr/lib/python2.7/dist-packages/networkx/utils/decorators.pyc in _open_file(func, *args, **kwargs)
    218         # Finally, we call the original function, making sure to close the fobj.
    219         try:
--> 220             result = func(*new_args, **kwargs)
    221         finally:
    222             if close_fobj:

/usr/lib/python2.7/dist-packages/networkx/readwrite/gml.pyc in read_gml(path, label, destringizer)
    208             yield line
    209 
--> 210     G = parse_gml_lines(filter_lines(path), label, destringizer)
    211     return G
    212 

/usr/lib/python2.7/dist-packages/networkx/readwrite/gml.pyc in parse_gml_lines(lines, label, destringizer)
    407             raise NetworkXError('node id %r is duplicated' % (id,))
    408         if label != 'id':
--> 409             label = pop_attr(node, 'node', 'label', i)
    410             if label in labels:
    411                 raise NetworkXError('node label %r is duplicated' % (label,))

/usr/lib/python2.7/dist-packages/networkx/readwrite/gml.pyc in pop_attr(dct, type, attr, i)
    397         except KeyError:
    398             raise NetworkXError(
--> 399                 "%s #%d has no '%s' attribute" % (type, i, attr))
    400 
    401     nodes = graph.get('node', [])

NetworkXError: node #0 has no 'label' attribute

我看到它抱怨因为节点没有标签。从GML的文档中我认为标签不是强制性的(也许我错了?)。有没有办法在没有标签的情况下阅读这样的文件?或者我应该更改我的gml文件? 谢谢你的帮助!

1 个答案:

答案 0 :(得分:6)

如果要在GML中使用id属性来标记节点,可以为nx.read_gml参数指定label属性,如下所示。

G = nx.read_gml('simple_graph.gml', label='id')