【问题标题】:read json graph networkx file读取json图networkx文件
【发布时间】:2020-07-27 22:06:47
【问题描述】:

我正在使用这个 Python 函数编写一个 networkx 图:

from networkx.readwrite import json_graph
def save_json(filename,graph):
    g = graph
    g_json = json_graph.node_link_data(g)
    json.dump(g_json,open(filename,'w'),indent=2)

并尝试使用以下方式加载图表:

def read_json_file(filename):
    graph = json_graph.loads(open(filename))
    return graph

读取函数取自here

我的问题是这给了我错误:

AttributeError: 'module' object has no attribute 'load'

这是有道理的,因为 networkx 文档中没有 load method

那么,我的问题是如何加载包含 networkx 图的 json 文件?

【问题讨论】:

  • json_graph.loadsjson_graph.load?
  • 也需要import json 声明...

标签: python json networkx


【解决方案1】:

鉴于official docs 所说的,我认为您正在寻找类似的东西

def read_json_file(filename):
    with open(filename) as f:
        js_graph = json.load(f)
    return json_graph.node_link_graph(js_graph)

即既然json文件是用json.dump写的,那么就用json.load把内容读回来。

然后从加载的字典创建图表。

注意:我从未使用过 json_graph 包,所以我忽略了正确的选项可能是为了重新创建您的特定类型的图形。您可能想在文档中浏览它们,似乎有很多。

【讨论】:

  • 如果您认为我的回答比其他人的回答正确并更好地解决了您的问题,请将其标记为已接受。谢谢。
  • 我想通过将js_graph = json.load(f) 更改为js_graph = json.loads(json.load(f)) 来改进这一点。 node_link_graph 函数接受 dict 对象。 json.load(f) 只会返回图形的字符串版本,因此我们必须将其转换回 dict。
  • json.load根据this table转换输入文件内容。如您所见,对象已作为字典返回
  • node_link_graph现在直接在主networkx包下,所以你可以做nx.node_link_graph(js_graph)
猜你喜欢
  • 1970-01-01
  • 2017-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多