【问题标题】:Converting a graphviz Source object to graphviz Graph object将 graphviz Source 对象转换为 graphviz Graph 对象
【发布时间】:2021-04-19 18:58:04
【问题描述】:

我有一个原始 .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'

【问题讨论】:

    标签: python graphviz dot


    【解决方案1】:

    我确实解析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)
           
    

    【讨论】:

      【解决方案2】:

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

      回答了该库不可能的问题,但可以使用其他库。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-19
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 2020-06-15
        • 2016-03-11
        • 2022-01-20
        相关资源
        最近更新 更多