将CSV转换为Newick树

发布于 2021-01-29 16:51:56

所以我有一个csv文件,其中每行代表以下形式的层次结构数据:“ Phylum”,“ Class”,“ Order”,“ Family”,“ Genus”,“
Species”,“ Subspecies”,“ unique_gi”

我想将其转换为经典的Newick树格式(无距离)。一种新颖的方法或一个python软件包都将是惊人的。谢谢!

关注者
0
被浏览
48
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    您可以使用一些简单的Python从CSV构建树,然后将其写到Newick树中。不确定这是否是您要尝试的操作。

    import csv
    from collections import defaultdict
    from pprint import pprint
    
    def tree(): return defaultdict(tree)
    
    def tree_add(t, path):
      for node in path:
        t = t[node]
    
    def pprint_tree(tree_instance):
        def dicts(t): return {k: dicts(t[k]) for k in t}
        pprint(dicts(tree_instance))
    
    def csv_to_tree(input):
        t = tree()
        for row in csv.reader(input, quotechar='\''):
            tree_add(t, row)
        return t
    
    def tree_to_newick(root):
        items = []
        for k in root.iterkeys():
            s = ''
            if len(root[k].keys()) > 0:
                sub_tree = tree_to_newick(root[k])
                if sub_tree != '':
                    s += '(' + sub_tree + ')'
            s += k
            items.append(s)
        return ','.join(items)
    
    def csv_to_weightless_newick(input):
        t = csv_to_tree(input)
        #pprint_tree(t)
        return tree_to_newick(t)
    
    if __name__ == '__main__':
        # see https://docs.python.org/2/library/csv.html to read CSV file
        input = [
            "'Phylum','Class','Order','Family','Genus','Species','Subspecies','unique_gi'", 
            "'Phylum','Class','Order','example'",
            "'Another','Test'",
        ]
    
        print csv_to_weightless_newick(input)
    

    输出示例:

    $ python ~/tmp/newick_tree.py
    (((example,((((unique_gi)Subspecies)Species)Genus)Family)Order)Class)Phylum,(Test)Another
    
    另外,该库看起来很酷,可以让您形象地看待树木:http
    //biopython.org/wiki/Phylo


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看