问题
I have a long GML file (Graph Modelling Language) that i am trying to read with Networkx in Python. In the GML file, nodes don't have label, like this:
graph [
node [
id 1
]
node [
id 2
]
edge [
source 2
target 1
]
]
I get an error when reading the file: 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
I see that it complains because the nodes don't have labels. From the documentation of GML i thought that labels were not obligatory (maybe i'm wrong?). Would there be a way to read such a file without labels? Or should i change my gml file? Thank you for your help!
回答1:
If you want to use id
attribute in GML for labeling nodes, you can designate the label attribute for the nx.read_gml
argument as follows.
G = nx.read_gml('simple_graph.gml', label='id')
来源:https://stackoverflow.com/questions/39200898/reading-a-gml-file-with-networkx-python-without-labels-for-the-nodes