本文目录导读:

- 方法一:使用 markmap(推荐,最简单)
- 方法二:Python + Graphviz
- 方法三:Python + 纯 HTML/CSS/JS
- 方法四:Shell 脚本生成简单文本思维导图
- 方法五:使用 mermaid.js(Web 方式)
- 推荐选择
我来介绍几种用脚本生成简单思维导图的方法,从命令行工具到纯代码实现。
使用 markmap(推荐,最简单)
markmap 可以将 Markdown 直接转换为思维导图:
# 安装 npm install -g markmap-cli # 创建一个 markdown 文件 example.md cat > example.md << 'EOF' # 学习计划 ## 编程语言 - Python - JavaScript - Java ## 数学基础 - 线性代数 - 概率论 - 微积分 ## 项目实践 - Web 开发 - 数据分析 EOF # 生成 HTML 思维导图 markmap example.md -o mindmap.html
Python + Graphviz
使用 Python 生成结构化格式的思维导图:
#!/usr/bin/env python3
"""生成简单的思维导图"""
import subprocess
import os
def create_mindmap(title, data, filename="mindmap.dot"):
"""生成 Graphviz DOT 格式的思维导图"""
dot_content = f'''
digraph MindMap {{
rankdir=LR; # 从左到右布局
node [shape=box, style=rounded, fillcolor=lightyellow, style="filled,rounded"];
edge [color=gray];
"{title}" [fillcolor=lightblue, fontsize=16];
'''
# 添加子节点
for parent, children in data.items():
dot_content += f' "{title}" -> "{parent}";\n'
for child in children:
if isinstance(child, tuple):
name, subs = child
dot_content += f' "{parent}" -> "{name}";\n'
for sub in subs:
dot_content += f' "{name}" -> "{sub}" [color=lightgray];\n'
else:
dot_content += f' "{parent}" -> "{child}";\n'
dot_content += '}'
# 写入文件
with open(filename, 'w', encoding='utf-8') as f:
f.write(dot_content)
# 生成图片
output_file = filename.replace('.dot', '.png')
subprocess.run(['dot', '-Tpng', filename, '-o', output_file])
print(f"思维导图已生成: {output_file}")
# 使用示例
if __name__ == "__main__":
data = {
"编程": [
("前端", ["HTML", "CSS", "JavaScript", "React"]),
("后端", ["Python", "Node.js", "Java"]),
("数据库", ["MySQL", "MongoDB"])
],
"工具": [
"Git",
"Docker",
("编辑器", ["VS Code", "Vim", "Sublime"])
]
}
create_mindmap("技能树", data)
Python + 纯 HTML/CSS/JS
不需要外部依赖,生成可交互的思维导图:
#!/usr/bin/env python3
"""生成交互式思维导图 HTML"""
import json
def create_interactive_mindmap(data, output="mindmap.html"):
"""创建可交互的 HTML 思维导图"""
html_template = f'''
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">思维导图</title>
<style>
* {{ margin: 0; padding: 0; box-sizing: border-box; }}
body {{ font-family: Arial, sans-serif; background: #f0f2f5; }}
#mindmap {{
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}}
.node {{
padding: 10px 20px;
margin: 5px;
border-radius: 8px;
cursor: pointer;
transition: all 0.3s;
text-align: center;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}}
.root {{
background: #4A90D9;
color: white;
font-size: 20px;
font-weight: bold;
}}
.level1 {{
background: #5CB85C;
color: white;
font-size: 16px;
}}
.level2 {{
background: #F0AD4E;
color: white;
font-size: 14px;
}}
.level3 {{
background: #D9534F;
color: white;
font-size: 12px;
}}
.container {{
display: flex;
flex-direction: column;
align-items: center;
}}
.children {{
display: flex;
justify-content: center;
flex-wrap: wrap;
margin-top: 20px;
position: relative;
}}
.connector {{
position: absolute;
width: 2px;
background: #ccc;
}}
</style>
</head>
<body>
<div id="mindmap">
<div id="tree-container"></div>
</div>
<script>
const data = {json.dumps(data, ensure_ascii=False)};
function createNode(name, level, children=[]) {{
const container = document.createElement('div');
container.className = 'container';
const node = document.createElement('div');
node.className = `node level${{Math.min(level, 3)}}`;
node.textContent = name;
container.appendChild(node);
if (children.length > 0) {{
const childrenContainer = document.createElement('div');
childrenContainer.className = 'children';
children.forEach(child => {{
if (typeof child === 'string') {{
childrenContainer.appendChild(createNode(child, level + 1));
}} else {{
childrenContainer.appendChild(createNode(child.name, level + 1, child.children));
}}
}});
container.appendChild(childrenContainer);
}}
return container;
}}
const tree = createNode(data.name, 0, data.children);
document.getElementById('tree-container').appendChild(tree);
</script>
</body>
</html>
'''
with open(output, 'w', encoding='utf-8') as f:
f.write(html_template)
print(f"交互式思维导图已生成: {output}")
# 使用示例
if __name__ == "__main__":
data = {
"name": "个人成长",
"children": [
{
"name": "技能提升",
"children": [
{"name": "编程", "children": ["Python", "JavaScript", "Go"]},
{"name": "设计", "children": ["UI/UX", "平面设计"]}
]
},
{
"name": "健康管理",
"children": ["运动", "饮食", "睡眠"]
},
{
"name": "休闲娱乐",
"children": ["阅读", "旅行", "摄影"]
}
]
}
create_interactive_mindmap(data)
Shell 脚本生成简单文本思维导图
#!/bin/bash
# gen_mindmap.sh - 生成文本思维导图
cat << 'EOF'
📚 学习路线图
├── 📖 基础知识
│ ├── 数据结构
│ │ ├── 数组
│ │ ├── 链表
│ │ └── 树
│ ├── 算法
│ │ ├── 排序
│ │ └── 搜索
│ └── 计算机网络
├── 💻 编程语言
│ ├── Python
│ │ ├── 基础语法
│ │ └── 框架
│ └── JavaScript
│ ├── ES6+
│ └── React/Vue
└── 🛠️ 工具链
├── Git
├── Docker
└── CI/CD
EOF
使用 mermaid.js(Web 方式)
#!/usr/bin/env python3
"""使用 Mermaid.js 生成思维导图 HTML"""
def create_mermaid_mindmap(data, output="mermaid_mindmap.html"):
"""生成 Mermaid 思维导图"""
mermaid_code = "mindmap\n"
mermaid_code += f" root(({data['name']}))\n"
def add_children(children, indent=2):
code = ""
for child in children:
if isinstance(child, str):
code += " " * indent + f"{child}\n"
elif isinstance(child, dict):
code += " " * indent + f"{child['name']}\n"
if 'children' in child:
code += add_children(child['children'], indent + 1)
return code
mermaid_code += add_children(data['children'])
html = f'''
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">Mermaid 思维导图</title>
<script src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
<script>
mermaid.initialize({{ startOnLoad: true }});
</script>
</head>
<body>
<div class="mermaid">
{mermaid_code}
</div>
</body>
</html>
'''
with open(output, 'w', encoding='utf-8') as f:
f.write(html)
print(f"Mermaid 思维导图已生成: {output}")
# 使用示例
if __name__ == "__main__":
data = {
"name": "项目计划",
"children": [
{"name": "需求分析", "children": ["用户调研", "竞品分析", "需求文档"]},
{"name": "设计阶段", "children": ["UI设计", "架构设计", "数据库设计"]},
{"name": "开发阶段", "children": ["前端开发", "后端开发", "API开发"]},
{"name": "测试部署", "children": ["单元测试", "集成测试", "部署上线"]}
]
}
create_mermaid_mindmap(data)
推荐选择
- 最快速:使用
markmap命令,直接从 Markdown 生成 - 最灵活:Python + Graphviz,可自定义样式和输出格式
- 最轻量:文本思维导图,无需任何依赖
- 最交互:HTML/JS 版本,可在浏览器中查看
- 最标准:Mermaid.js 版本,支持多种图表类型
选择最适合你需求的方法即可!