You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Graphviz生成的SVG图转换回DOT语言?

把Graphviz SVG转基础DOT的可行方案

有几种实用的方法可以实现,不用保留样式,只提取节点、边和标签:

1. 写个简单的Python脚本(最靠谱)

Graphviz生成的SVG结构非常规整,直接解析元素就能拿到需要的信息。用BeautifulSoup或者lxml这类库就能快速实现:

示例脚本

from bs4 import BeautifulSoup

def svg_to_dot(svg_file_path):
    # 读取并解析SVG文件
    with open(svg_file_path, 'r', encoding='utf-8') as f:
        soup = BeautifulSoup(f, 'xml')
    
    dot_content = ['digraph G {']
    
    # 提取所有节点
    node_groups = soup.find_all('g', class_='node')
    for node in node_groups:
        # 从节点ID里提取标识(Graphviz生成的节点ID一般带node-前缀)
        node_id = node['id'].replace('node-', '')
        # 提取节点标签,没有的话用节点ID代替
        node_label = node.find('text').text.strip() if node.find('text') else node_id
        dot_content.append(f'    {node_id} [label="{node_label}"];')
    
    # 提取所有边
    edge_groups = soup.find_all('g', class_='edge')
    for edge in edge_groups:
        source = edge['source'].replace('node-', '')
        target = edge['target'].replace('node-', '')
        # 提取边标签,没有就留空
        edge_label = edge.find('text').text.strip() if edge.find('text') else ''
        if edge_label:
            dot_content.append(f'    {source} -> {target} [label="{edge_label}"];')
        else:
            dot_content.append(f'    {source} -> {target};')
    
    dot_content.append('}')
    return '\n'.join(dot_content)

# 使用方式:替换成你的SVG文件路径
print(svg_to_dot('your_graph.svg'))

这个脚本适配大部分Graphviz生成的SVG,要是你的SVG结构有点特殊,调整下标签选择器就行。

2. 间接转换(不推荐,准确率低)

如果不想写代码,也可以走中间格式,但效果不如直接解析SVG:

  • 用Inkscape或者ImageMagick把SVG转成PDF:inkscape input.svg --export-type=pdf
  • 再用专门的工具从PDF里提取图形结构转成DOT,但这种方法容易丢失节点/边的标识,只适合简单图形。

内容的提问来源于stack exchange,提问作者user35603

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 00:52:40