我正在拼命寻找创建一个漂亮的二叉树图的解决方案。至关重要的是,不完整的节点具有可区分的边缘(如果有的话)。
我无法使用.dot生成所需的结果,因为我知道无法订购节点。我不介意,将文件导入yEd或其他编辑器。但是,我希望能够用很少的语法轻松生成数据。
我的目标是生成例如来自简约数据的.graphml格式,例如(A(B1 C1 C2)B2),其中A是根标签,B1是根的左子,另有两个子。与.dot或.tgf类似的复杂性当然是可以容忍的,但我想避免自己编写编译器来生成.graphml。
任何想法都赞赏。
Markus R。
答案 0 :(得分:1)
您提供的数据或多或少为s-expression。鉴于这是您要摄取的格式,pyparsing(Python模块)具有s-expression parser。
您还需要一个图库。我的大部分工作都使用networkx。使用pyparsing s-expression解析器和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是一个很好的图形库,如果需要,您可以编写其他代码来遍历树,以使用其他元数据标记边或节点。