データは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は良いグラフライブラリですし、必要に応じて、追加のメタデータでエッジまたはノードをタグ付けするためにあなたの木の上に歩く追加のコードを書くことができます。
あなたは何を意味していますか?空のノードが使用されている場合にのみ.dotで動作しますか? – marapet
つまり、私は不可視の仮想ノード(リーフ)を使用してエッジを指示する必要があります。 –
グラフを可視化する際に、仮想ノードを避ける理由は何ですか? – parselmouth