Merge two dot graphs at a common node in python

前提是你 提交于 2020-01-23 04:09:07

问题


The dependency-parsed output (using Stanford Parser) of the following two sentences are as follows.

Sentence 1 - John is a computer scientist

Dot format -

digraph G{
edge [dir=forward]
node [shape=plaintext]

0 [label="0 (None)"]
0 -> 5 [label="root"]
1 [label="1 (John)"]
2 [label="2 (is)"]
3 [label="3 (a)"]
4 [label="4 (computer)"]
5 [label="5 (scientist)"]
5 -> 2 [label="cop"]
5 -> 4 [label="compound"]
5 -> 3 [label="det"]
5 -> 1 [label="nsubj"]
}

Graph -

Sentence 2 - John has an elder sister named Mary.

Dot Format -

digraph G{
edge [dir=forward]
node [shape=plaintext]

0 [label="0 (None)"]
0 -> 2 [label="root"]
1 [label="1 (John)"]
2 [label="2 (has)"]
2 -> 5 [label="dobj"]
2 -> 1 [label="nsubj"]
3 [label="3 (an)"]
4 [label="4 (elder)"]
5 [label="5 (sister)"]
5 -> 6 [label="acl"]
5 -> 3 [label="det"]
5 -> 4 [label="amod"]
6 [label="6 (named)"]
6 -> 7 [label="dobj"]
7 [label="7 (Mary)"]
}

Graph -

Now I want to merge these graphs at a common node, John. I am currently using graphviz to import dot graph like this,

from graphviz import Source
s = Source(dotGraph, filename=filepath, format="png")

But there seems to be no functionality to merge graphs in Graphviz, or Networkx. So how can this be done?


回答1:


The way to merge the two graphs would be defining a single digraph having two subgraphs.

from graphviz import Source

clusters = """
digraph G{

subgraph cluster0 {
    edge [dir=forward]
    node [shape=plaintext]

    0 [label="0 (None)"]
    0 -> 5 [label="root"]
    1 [label="1 (John)"]
    2 [label="2 (is)"]
    3 [label="3 (a)"]
    4 [label="4 (computer)"]
    5 [label="5 (scientist)"]
    5 -> 2 [label="cop"]
    5 -> 4 [label="compound"]
    5 -> 3 [label="det"]
    5 -> 1 [label="nsubj"]
}

subgraph cluster1 {
edge [dir=forward]
node [shape=plaintext]

0 [label="0 (None)"]
0 -> 2 [label="root"]
1 [label="1 (John)"]
2 [label="2 (has)"]
2 -> 5 [label="dobj"]
2 -> 1 [label="nsubj"]
3 [label="3 (an)"]
4 [label="4 (elder)"]
5 [label="5 (sister)"]
5 -> 6 [label="acl"]
5 -> 3 [label="det"]
5 -> 4 [label="amod"]
6 [label="6 (named)"]
6 -> 7 [label="dobj"]
7 [label="7 (Mary)"]
}
}
"""



src = Source(clusters, format='png')
src.render("graphing1", view=True)


来源:https://stackoverflow.com/questions/42041494/merge-two-dot-graphs-at-a-common-node-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!