您提供的数据是更多或更少的s-expression。鉴于这是你想要获取的格式,pyparsing(一个Python模块)有一个s-expression parser。
您还需要一个图库。我的大部分工作都使用networkx。随着pyparsing s表达式解析器和networkx,下面的代码提取数据,并创建一个树作为一个有向图:
import networkx as nx
def build(g, X):
if isinstance(X, list):
parent = X[0]
g.add_node(parent)
for branch in X[1:]:
child = build(g, branch)
g.add_edge(parent, child)
return parent
if isinstance(X, basestring):
g.add_node(X)
return X
#-- The sexp parser is constructed by the code example at...
#-- http://http://pyparsing.wikispaces.com/file/view/sexpParser.py
sexpr = sexp.parseString("(A (B1 C1 C2) B2)", parseAll = True)
#-- Get the parsing results as a list of component lists.
nested = sexpr.asList()
#-- Construct an empty digraph.
dig = nx.DiGraph()
#-- build the tree
for component in nested:
build(dig, component)
#-- Write out the tree as a graphml file.
nx.write_graphml(dig, 'tree.graphml', prettyprint = True)
为了验证这一点,我也写了树作为.DOT文件,并使用graphviz的创建下面的图片:

networkx是一个很好的图形库,你可以写走到你的树,如果需要额外的元数据标记边缘或节点,额外的代码。
这是什么意思_This只适用于.dot空节点_? – marapet
也就是说,我必须使用不可见的虚拟节点(叶子)来指引边缘。 –
在可视化图形中,为什么要避免使用虚拟节点? – parselmouth