简体   繁体   English

如何保存“pos 字典”类型的对象? (网络 X)

[英]How to save a 'pos dictionary' type of object? (NetworkX)

I am using the networkx as nx .我使用networkx as nx After creating a graph object (G), I use the data = nx.spring_layout(G) method to generate a dictionary (pos).创建图形对象(G)后,我使用data = nx.spring_layout(G)方法生成字典(pos)。 Generating this pos object is very time-consuming and I want to save it as a file, so I don't have to rerun it all whenever I want to work with this dataset.生成这个pos对象非常耗时,我想将它保存为一个文件,因此每当我想使用这个数据集时,我都不必重新运行它。 This is what it looks like so far:这是到目前为止的样子:

G = nx.Graph()
G.add_edges_from(tuples)
data = nx.spring_layout(G)

If I run type(data) , I receive 'dict'.如果我运行type(data) ,我会收到“dict”。 If I run type(G), I receive 'networkx.classes.graph.Graph'.如果我运行 type(G),我会收到“networkx.classes.graph.Graph”。

Since it is a 'dict' object, these are some solutions I found online that I tried and didn't work:由于它是一个“dict”对象,因此这些是我在网上找到的一些解决方案,我尝试过但没有奏效:

1. Save it as a .csv file 1. 将其另存为 .csv 文件

import csv

w = csv.writer(open("output.csv", "w"))

for key, val in data.items():
    w.writerow([key, val])

2. Save as JSON file 2.另存为JSON文件

import json
json = json.dumps(data)


f = open("data.json","w")

f.write(json)

f.close()

3. Save as a .txt file 3.另存为.txt文件

f = open("data.txt","w")

f.write( str(data) )

f.close()

Hopefully I made it clear that (i) I don't know which type of file is the best one to save this sort of object;希望我明确表示(i)我不知道哪种类型的文件最适合保存此类对象; that (ii) I don't know how to save it in any way; (ii) 我不知道如何以任何方式保存它; and (iii) that, naturally, I don't know how to properly load this file as 'pos dict' object once it is saved in my directory. (iii) 自然,我不知道如何将此文件正确加载为“pos dict”对象,一旦它保存在我的目录中。

For reference, nx.spring_layout(G) returns: " pos : dict A dictionary of positions keyed by node.", as described in the documentation .作为参考,nx.spring_layout(G) 返回:“ pos : dict A dictionary of position keyed by node.”,如文档中所述。

Probably the simplest way to store a python object for later use is to use the pickle module:可能存储 python 对象以供以后使用的最简单方法是使用pickle模块:

import pickle

# save data
with open('positions.pickle', 'wb') as f:
    pickle.dump(data, f)

# load data
with open('positions.pickle', 'rb') as f:
    data = pickle.load(f)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM