python

关注公众号 jb51net

关闭
首页 > 脚本专栏 > python > Python数据生成思维导图

Python实现JSON数据动态生成思维导图图片

作者:大霸王龙

这篇文章主要为大家详细介绍了Python如何实现将JSON格式数据动态生成思维导图图片,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下

要实现将JSON格式数据动态生成思维导图图片,可以使用`pygraphviz`库结合`json`解析。以下是完整实现代码:

import json
import pygraphviz as pgv
from io import BytesIO

def generate_mindmap(data):
    # 创建有向图
    graph = pgv.AGraph(directed=True, layout="dot", rankdir="LR")
    
    # 添加根节点
    root_id = data["id"]
    graph.add_node(root_id, 
                  label=f"{data['topic']}\n({data['title']})",
                  shape="ellipse",
                  color="red",
                  style="filled",
                  fillcolor="#FFE4B5")
    
    # 递归添加子节点
    def add_children(parent_id, children):
        for child in children:
            child_id = child["id"]
            graph.add_node(child_id, 
                          label=child["topic"],
                          shape="box",
                          color="blue")
            graph.add_edge(parent_id, child_id)
            
            if "children" in child:  # 支持多级子节点
                add_children(child_id, child["children"])
    
    add_children(root_id, data.get("children", []))
    
    # 生成图片二进制数据
    graph.layout(prog="dot")
    temp = BytesIO()
    graph.draw(temp, format="png")
    temp.seek(0)
    return temp

# 示例数据(替换为你的实际数据)
method = [
    "create: 创建新节点",
    "update: 更新节点内容",
    "delete: 删除指定节点",
    "move: 移动节点位置"
]

data = {
    "id": "root",
    "topic": "jsMind",
    "title": "中心主题",
    "children": [
        {
            "id": line.split(":").strip(),
            "topic": line.split(":")[-1].strip(),
        }
        for line in method
        if len(line.split(":").strip()) > 0
    ]
}

# 生成并保存图片
image_data = generate_mindmap(data)
with open("mindmap.png", "wb") as f:
    f.write(image_data.getvalue())

print("思维导图已生成:mindmap.png")

效果说明:

Gradio集成方案(结合展示):

import gradio as gr

def visualize_mindmap(method_text):
    method = [line.strip() for line in method_text.split("\n") if line.strip()]
    
    data = {
        "id": "root",
        "topic": "jsMind",
        "title": "中心主题",
        "children": [
            {
                "id": line.split(":").strip(),
                "topic": line.split(":")[-1].strip(),
            }
            for line in method
            if len(line.split(":").strip()) > 0
        ]
    }
    
    return generate_mindmap(data).getvalue()

iface = gr.Interface(
    fn=visualize_mindmap,
    inputs=gr.Textbox(label="输入方法(每行格式:id: 描述)", lines=5),
    outputs=gr.Image(label="动态思维导图"),
    examples=[
        ["create: 创建新节点\nupdate: 更新节点内容\ndelete: 删除指定节点\nmove: 移动节点位置"]
    ]
)

iface.launch()

使用前需安装依赖:

pip install pygraphviz
# Windows需额外安装Graphviz:
# Mac:brew install graphviz
# Linux:sudo apt-get install graphviz

该方案特点:

以上就是Python实现JSON数据动态生成思维导图图片的详细内容,更多关于Python数据生成思维导图的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
阅读全文