我有两个文件。第一个文件具有边和权重,格式如下:
1 3 1
2 4 1
2 5 1 etc
第二个文件有节点id和节点的属性:
^{pr2}$使用第一个文件,我使用以下代码创建有向图:
G = nx.read_edgelist('myGraph.txt', create_using=nx.DiGraph(), delimiter='\t', nodetype=int, data=(('sign', int),))
接下来我用第二个文件来读每一行。我读取第一个标记(node id),检查这个节点是否属于我的图节点,然后再次使用split函数删除逗号。现在我想将属性保存到node。我使用下面的代码,但是属性保持空白。这是我的代码:
for line in file2:
words = line.split()
node = words[0]
attributes = words[1]
splittedAttributes = attributes.split(',')
G.node[node]['Attributes'] = splittedAttributes
你的代码有一个小错误:
}也是
^{pr2}$nodetype=int
您正在以int
的形式加载节点。因为line
是str
,那么{str
。如果要使用ints
,请执行以下操作:这应该能解决问题。记住以}的权重,这会引发错误。在
G.node[node]['Attributes']
而不是G[node]['Attributes']
的形式访问属性,因为这样会输出节点node
和{相关问题 更多 >
编程相关推荐