所以我有一个csv文件,其中每一行代表以下形式的分层数据: '动物门''级''令''家庭''属''物种& #39;,'亚种'' unique_gi'
我想将此转换为经典的Newick tree format sans距离。无论是新方法还是python包都会令人惊叹。谢谢!
答案 0 :(得分:6)
您可以使用一些简单的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