如何写思维导图导出脚本

wen 实用脚本 27

本文目录导读:

如何写思维导图导出脚本

  1. XMind 导出脚本 (Python)
  2. Markdown 导出脚本
  3. JSON 格式导出
  4. 通用导出工具类
  5. 命令行工具版本
  6. 使用建议

我来介绍几种常见的思维导图导出脚本实现方法。

XMind 导出脚本 (Python)

import xmind
from xmind.core.markerref import MarkerId
def export_to_xmind(data, filename):
    """导出思维导图到 XMind 格式"""
    workbook = xmind.Workbook()
    sheet = workbook.getPrimarySheet()
    sheet.setTitle("思维导图")
    root = sheet.getRootTopic()
    root.setTitle(data['title'])
    def add_nodes(parent, children):
        for item in children:
            topic = parent.addSubTopic()
            topic.setTitle(item.get('title', ''))
            if item.get('note'):
                topic.setNote(item['note'])
            if item.get('markers'):
                for marker in item['markers']:
                    topic.addMarker(MarkerId(marker))
            if item.get('children'):
                add_nodes(topic, item['children'])
    if data.get('children'):
        add_nodes(root, data['children'])
    xmind.save(workbook, filename)
    print(f"导出成功: {filename}")
# 使用示例
data = {: '项目计划',
    'children': [
        {
            'title': '需求分析',
            'children': [
                {'title': '用户调研'},
                {'title': '竞品分析'}
            ]
        },
        {
            'title': '设计开发',
            'children': [
                {'title': 'UI设计'},
                {'title': '后端开发'}
            ]
        }
    ]
}
export_to_xmind(data, 'project_plan.xmind')

Markdown 导出脚本

def export_to_markdown(data, filename):
    """导出思维导图到 Markdown 格式"""
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(f"# {data['title']}\n\n")
        def write_nodes(items, level=1):
            for item in items:
                prefix = '  ' * level
                f.write(f"{prefix}- {item['title']}\n")
                if item.get('note'):
                    f.write(f"{prefix}  > {item['note']}\n")
                if item.get('children'):
                    write_nodes(item['children'], level + 1)
        if data.get('children'):
            write_nodes(data['children'])
    print(f"导出成功: {filename}")
# 使用示例
data = {: '学习路线',
    'children': [
        {
            'title': '基础知识',
            'note': '打好基础很重要',
            'children': [
                {'title': 'Python基础'},
                {'title': '数据结构'}
            ]
        },
        {
            'title': '进阶学习',
            'children': [
                {'title': 'Web开发'},
                {'title': '数据分析'}
            ]
        }
    ]
}
export_to_markdown(data, 'mindmap.md')

JSON 格式导出

import json
def export_to_json(data, filename):
    """导出思维导图到 JSON 格式"""
    def clean_data(node):
        """清理数据,移除空字段"""
        result = {'title': node.get('title', '')}
        if node.get('note'):
            result['note'] = node['note']
        if node.get('children'):
            result['children'] = [clean_data(child) for child in node['children'] if child.get('title')]
        return result
    clean = clean_data(data)
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(clean, f, ensure_ascii=False, indent=2)
    print(f"导出成功: {filename}")
# 或者导出为缩略版本
def export_to_compact_json(data, filename):
    """导出紧凑格式的 JSON"""
    def flatten(node, path=''):
        result = {}
        current_path = f"{path}/{node['title']}" if path else node['title']
        result[current_path] = node.get('note', '')
        for child in node.get('children', []):
            result.update(flatten(child, current_path))
        return result
    flat_data = flatten(data)
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(flat_data, f, ensure_ascii=False, indent=2)
    print(f"导出成功: {filename}")

通用导出工具类

class MindMapExporter:
    """思维导图导出器"""
    SUPPORTED_FORMATS = ['xmind', 'markdown', 'json', 'text', 'html']
    def __init__(self, data):
        self.data = data
    def export(self, format_type, filename):
        """导出指定格式"""
        if format_type not in self.SUPPORTED_FORMATS:
            raise ValueError(f"不支持的格式: {format_type}")
        export_method = getattr(self, f'_export_to_{format_type}')
        export_method(filename)
    def _export_to_text(self, filename):
        """导出为纯文本
        root
        ├── child1
        │   ├── grandchild1
        │   └── grandchild2
        └── child2
        """
        def write_tree(node, prefix='', is_last=True):
            result = []
            connector = '└── ' if is_last else '├── '
            result.append(f"{prefix}{connector}{node['title']}\n")
            children = node.get('children', [])
            for i, child in enumerate(children):
                new_prefix = prefix + ('    ' if is_last else '│   ')
                result.extend(write_tree(child, new_prefix, i == len(children)-1))
            return result
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(f"{self.data['title']}\n")
            if self.data.get('children'):
                for i, child in enumerate(self.data['children']):
                    is_last = i == len(self.data['children']) - 1
                    f.writelines(write_tree(child, '', is_last))
        print(f"导出成功: {filename}")
    def _export_to_html(self, filename):
        """导出为 HTML 格式"""
        html_template = """
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="UTF-8">
            <title>{title}</title>
            <style>
                ul {{ list-style: none; padding-left: 20px; }}
                li {{ margin: 5px 0; }}
                .node {{ display: inline-block; padding: 5px 10px; 
                        background: #f0f0f0; border-radius: 3px; }}
                .note {{ color: #666; font-size: 0.9em; margin: 2px 0 0 20px; }}
            </style>
        </head>
        <body>
            <h1>{title}</h1>
            {content}
        </body>
        </html>
        """
        def build_html(node):
            html = f'<li><span class="node">{node["title"]}</span>'
            if node.get('note'):
                html += f'<div class="note">{node["note"]}</div>'
            if node.get('children'):
                html += '<ul>'
                for child in node['children']:
                    html += build_html(child)
                html += '</ul>'
            html += '</li>'
            return html
        content = '<ul>' + ''.join(build_html(child) for child in self.data.get('children', [])) + '</ul>'
        with open(filename, 'w', encoding='utf-8') as f:
            f.write(html_template.format(
                title=self.data['title'],
                content=content
            ))
        print(f"导出成功: {filename}")
# 使用示例
exporter = MindMapExporter(data)
exporter.export('text', 'mindmap.txt')
exporter.export('html', 'mindmap.html')

命令行工具版本

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import sys
def main():
    parser = argparse.ArgumentParser(description='思维导图导出工具')
    parser.add_argument('-i', '--input', required=True, help='输入文件 (JSON格式)')
    parser.add_argument('-o', '--output', required=True, help='输出文件')
    parser.add_argument('-f', '--format', choices=['xmind', 'md', 'json', 'txt', 'html'],
                       default='md', help='导出格式')
    args = parser.parse_args()
    # 读取输入文件
    with open(args.input, 'r', encoding='utf-8') as f:
        data = json.load(f)
    # 根据格式导出
    exporter = MindMapExporter(data)
    format_map = {
        'xmind': 'xmind',
        'md': 'markdown',
        'json': 'json',
        'txt': 'text',
        'html': 'html'
    }
    exporter.export(format_map[args.format], args.output)
if __name__ == '__main__':
    main()

使用建议

  1. 选择合适格式

    • XMind:适合需要继续编辑的场景
    • Markdown:适合文档集成
    • JSON:适合程序处理
    • 文本/HTML:适合分享展示
  2. 数据处理

    • 先清洗和验证数据
    • 添加错误处理机制
    • 支持批量导出
  3. 扩展功能

    • 添加图片支持
    • 支持自定义样式
    • 实现导入功能

这些脚本可以根据实际需求进行修改和扩展。

抱歉,评论功能暂时关闭!