将图形对象写入dimacs文件窗体

2024-05-18 07:53:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用networkx库创建了一个graph对象,代码如下。在

import networkx as nx

#Convert snap dataset to graph object
g = nx.read_edgelist('com-amazon.ungraph.txt',create_using=nx.Graph(),nodetype = int)
print(nx.info(g))

不过,我需要将graph对象写入dimacs文件格式,我相信networkx的函数不包含这种格式。有办法吗?在


Tags: to对象代码importnetworkxcomconvertread
1条回答
网友
1楼 · 发布于 2024-05-18 07:53:37

http://prolland.free.fr/works/research/dsat/dimacs.html上描述的规范非常简单,因此您只需执行以下操作:

g = nx.house_x_graph() # stand-in graph since we don't have your data
dimacs_filename = "mygraph.dimacs" 

with open(dimacs_filename, "w") as f:
    # write the header
    f.write("p EDGE {} {}\n".format(g.number_of_nodes(), g.number_of_edges()))
    # now write all edges
    for u, v in g.edges():
        f.write("e {} {}\n".format(u, v))

这将生成文件“我的图形.dimacs“:

^{pr2}$

相关问题 更多 >