使用networkx(python)读取没有节点标签的GML文件 [英] reading a GML file with networkx (python) without labels for the nodes
问题描述
我有一个很长的GML文件(图形建模语言),我正试图用Networkx在Python中读取它. 在GML文件中,节点没有标签,如下所示:
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
]
]
读取文件时出现错误: G = nx.read_gml('simple_graph.gml')
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
我看到它抱怨是因为节点没有标签.从GML的文档中,我认为标签不是强制性的(也许我错了吗?).有没有办法读取没有标签的文件?还是我应该更改我的gml文件? 谢谢您的帮助!
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!
推荐答案
如果要在GML中使用id
属性标记节点,则可以按以下方式为nx.read_gml
参数指定label属性.
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')
这篇关于使用networkx(python)读取没有节点标签的GML文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!