将graphviz源对象转换为graphviz图形对象

2024-06-09 22:24:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个以raw.dot格式制作的模板原理图,但现在我想用python填充标签

使用https://pypi.org/project/graphviz/库,我成功加载了.dot文件,但不知道如何编辑它。是否可以将Source对象转换为Graph对象,或者使用Graph对象可用的方法

尝试:

from graphviz import Source

src = Source('digraph "the holy hand grenade" { rankdir=LR; 1 -> 2 -> 3 -> lob }')
src.node("foo")
_ = src.render('test.gv', view=False)
Source.from_file('test.gv')

我得到了错误AttributeError: 'Source' object has no attribute 'node'


Tags: 对象fromtestsrc模板nodesourceraw
2条回答

https://github.com/xflr6/graphviz/issues/76

回答了这样一个问题,即该库不可能实现,但可以使用其他库

我会解析grapviz.source消除不必要的字符并追加回。这是我的工作。注意,假设第一行可能包含注释。剩下的就是让它成为功能

src = Source.from_file('Source.gv')
lst = str(src).splitlines()
HasComment =  (lst[0].find('//') != -1)

IsDirectGraph = False
skipIndex  = 0

if HasComment:
    skipIndex = 1
    if lst[skipIndex].find('graph {')!=-1 :
        IsDirectGraph= False
else:
    if lst[0].find('graph {')!=-1 :
        IsDirectGraph= False 

if IsDirectGraph:
    g = Digraph()
else:
    g = Graph()
    
g.body.clear()
        
s = str()
for i in range(len(lst)):
    if( (i>skipIndex) and (i!=len(lst)-1) ):
        if HasComment:
            g.comment = lst[0].replace('//','')
        g.body.append(lst[i])
print(g.source)       
display(g)
       

相关问题 更多 >