使用没有节点标签的 networkx (python) 读取 GML 文件

reading a GML file with networkx (python) without labels for the nodes

我有一个很长的 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 文件? 感谢您的帮助!

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

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