gpt4 book ai didi

python - 目标与 networkx json 文件中的节点 ID 不匹配

转载 作者:太空宇宙 更新时间:2023-11-03 16:17:53 25 4
gpt4 key购买 nike

我有一个网络,我想输出到 json 文件。但是,当我输出它时,节点目标会转换为数字,并且与作为字符串的节点 ID 不匹配。

例如:

G = nx.DiGraph(data)
G.edges()

结果:

[(22, 'str1'),
(22, 'str2'),
(22, 'str3')]

在Python中。这是正确的。

但是在输出中,当我像这样写出数据时......

json.dump(json_graph.node_link_data(G), f, 
indent = 4, sort_keys = True, separators=(',',':'))

而三个目标节点“str1”、“str2”和“str3”的 id...

{
"id":"str1"
},
{
"id":"str2"
},
{
"id":"str3"
}

节点22的目标已变成数字

    {
"source":22,
"target":972
},
{
"source":22,
"target":1261
},
{
"source":22,
"target":1259
}

所有具有字符串 ID 的节点都会发生这种情况

为什么会这样,我该如何预防?

期望的结果是“目标”字段应保留字符串 ID,或者字符串 ID 以与目标匹配的方式变为数字。

最佳答案

Why is this

这是一个功能。并非所有图形库都接受字符串作为标识符,但我所知道的所有图形库都接受整数。

how can I prevent it?

使用 nodes 映射将 id 替换为节点名称:

>>> import networkx as nx
>>> import pprint
>>> g = nx.DiGraph()
>>> g.add_edge(1, 'foo')
>>> g.add_edge(2, 'bar')
>>> g.add_edge('foo', 'bar')
>>> res = nx.node_link_data(g)
>>> pprint.pprint(res)
{'directed': True,
'graph': {},
'links': [{'source': 0, 'target': 3},
{'source': 1, 'target': 2},
{'source': 3, 'target': 2}],
'multigraph': False,
'nodes': [{'name': 1}, {'name': 2}, {'name': 'bar'}, {'name': 'foo'}]}
>>> res['links'] = [
{
'source': res['nodes'][link['source']]['name'],
'target': res['nodes'][link['target']]['name']
}
for link in res['links']]
>>> pprint.pprint(res)
{'directed': True,
'graph': {},
'links': [{'source': 1, 'target': 'foo'},
{'source': 2, 'target': 'bar'},
{'source': 'foo', 'target': 'bar'}],
'multigraph': False,
'nodes': [{'name': 1}, {'name': 2}, {'name': 'bar'}, {'name': 'foo'}]}

关于python - 目标与 networkx json 文件中的节点 ID 不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38757701/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com