Skip to main content
 首页 » 编程设计

python之使用 Networkx,如何将 graphml 和其他格式写入字符串而不是文件

2025年05月04日20softidea

我对 networkx 的使用非常肤浅。将图形写入文件(如 graphml)很容易,但如何在不影响文件系统的情况下将其保存为字符串?

Its doc说这是可能的。

请您参考如下方法:

大多数格式也有一个“生成器”。所以你可以这样做而不使用 StringIO:

In [1]: import networkx as nx 
 
In [2]: G=nx.path_graph(4) 
 
In [3]: s='\n'.join(nx.generate_graphml(G)) 
 
In [4]: print s 
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd"> 
  <key attr.name="name" attr.type="string" for="graph" id="d0" /> 
  <graph edgedefault="undirected"> 
    <data key="d0">path_graph(4)</data> 
    <node id="0" /> 
    <node id="1" /> 
    <node id="2" /> 
    <node id="3" /> 
    <edge source="0" target="1" /> 
    <edge source="1" target="2" /> 
    <edge source="2" target="3" /> 
  </graph> 
</graphml>