Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 以newick格式保存NetworkX树_Python_Networkx - Fatal编程技术网

Python 以newick格式保存NetworkX树

Python 以newick格式保存NetworkX树,python,networkx,Python,Networkx,我在networkx中创建了一个图,并得到了它的bfs树 G = nx.Graph() # build a graph tree = nx.bfs_tree(G, '1') 现在我想将树保存到一个文件中。做这件事最好的方法是什么?受此启发,我做了如下事情: import networkx as nx import matplotlib.pyplot as plt def recursive_search(dict, key): if key in dict: re

我在
networkx
中创建了一个图,并得到了它的bfs树

G = nx.Graph()

# build a graph

tree = nx.bfs_tree(G, '1')
现在我想将树保存到一个文件中。做这件事最好的方法是什么?

受此启发,我做了如下事情:

import networkx as nx
import matplotlib.pyplot as plt

def recursive_search(dict, key):
    if key in dict:
        return dict[key]
    for k, v in dict.items():
        item = recursive_search(v, key)
        if item is not None:
            return item

def bfs_edge_lst(graph, n):
    return list(nx.bfs_edges(graph, n))

def load_graph(filename):
    G = nx.Graph()
    # build the graph
    return G

def tree_from_edge_lst(elst):
    tree = {'1': {}}
    for src, dst in elst:
        subt = recursive_search(tree, src)
        subt[dst] = {}
    return tree

def tree_to_newick(tree):
    items = []
    for k in tree.keys():
        s = ''
        if len(tree[k].keys()) > 0:
            subt = tree_to_newick(tree[k])
            if subt != '':
                s += '(' + subt + ')'
        s += k
        items.append(s)
    return ','.join(items)

g = load_graph('dataset.txt')
elst = bfs_edge_lst(g, '1')
tree = tree_from_edge_lst(elst)
newick = tree_to_newick(tree) + ';'

受@hklel答案的启发,我编写了以下代码:

将networkx导入为nx
def tree_to_newick(g,root=None):
如果root为None:
根=列表(过滤器(lambda p:p[1]==0,g.in_degree())
断言1==len(根)
根=根[0][0]
subgs=[]
对于g[root]中的子级:
如果len(g[child])>0:
subgs.append(tree_to_newick(g,root=child))
其他:
附加子项(子项)
返回“(“+”,“.join(subgs)+”)
树到纽维克(nx.Graph(),无)
它似乎起作用了