🚀

科研项目结构初始化

一键生成标准项目目录

专为医学博士设计的项目结构,一键生成Scripts、Templates、Input、Results等标准目录, 同时创建Python和R脚本模板、Rproj工程文件,自动设置文件夹视图。

✨ 核心特性

📁

标准目录结构

符合医学科研规范的目录组织

📝

双语言模板

自动生成Python和R脚本模板

🎨

视图自动设置

列表视图、名称排序、自动展开

📂 生成的目录结构

项目文件夹/
├── 01_Scripts/
│   ├── 00_Templates/      # 脚本模板(Python + R)
│   │   ├── 01_Data_Cleaning.py
│   │   ├── 01_Data_Cleaning.R
│   │   ├── 02_Baseline_Table1.py
│   │   ├── 02_Baseline_Table1.R
│   │   ├── 03_Models_Survival_Reg.py
│   │   ├── 03_Models_Survival_Reg.R
│   │   └── ...
│   └── 99_Archive/        # 历史代码存档
├── 02_Input/              # 外部数据(只读)
├── 03_Results/
│   ├── 01_Final/          # 最终图表
│   ├── 02_Stages/         # 中间结果
│   └── 99_Archive/        # 结果存档
├── 04_Docs/               # 文档和日志
│   └── 99_Archive/
└── 项目名.Rproj           # RStudio工程文件
💡 设计理念
  • Input只读:防止误修改原始数据
  • Templates分离:保持Scripts目录整洁
  • Archive机制:方便版本管理和回溯
  • Rproj集成:双击即可用RStudio打开

🔧 Automator设置

创建快速操作

  1. 打开 Automator.app
  2. 选择 "快速操作"
  3. 设置工作流程:
    • 工作流程收到当前:文件夹
    • 位于:访达.app
    • 传递输入:作为自变量
  4. 添加 "运行Shell脚本" 动作
  5. Shell选择:/bin/bash

Shell脚本内容

复制以下代码到Automator,记得修改第16行的Python路径

# 1. 替换为你自己的Python路径
PYTHON_EXEC="/Users/你的用户名/miniconda3/bin/python"

# 2. 调用Python脚本
"$PYTHON_EXEC" - "$@" <<'EOF'

import sys
import os
import subprocess
from pathlib import Path

# ================= 配置区域 =================

# 1. 文件夹结构列表
STRUCTURE_LIST = [
    "01_Scripts",
    "01_Scripts/00_Templates",
    "01_Scripts/99_Archive",
    "02_Input",
    "03_Results/01_Final",
    "03_Results/02_Stages",
    "03_Results/99_Archive",
    "04_Docs",
    "04_Docs/99_Archive",
]

# 2. 医学博士专用脚本模板名称
# 会同时生成Python (.py) 和R (.R) 版本
SCRIPT_BASENAMES = [
    "01_Data_Cleaning",        # 数据清洗
    "02_Baseline_Table1",      # 基线资料
    "03_Models_Survival_Reg",  # Cox/Logistic回归
    "04_Subgroup_Sensitivity", # 亚组分析
    "05_Plots_Visualization",  # 可视化
    "99_Utils_Config",        # 工具库
]

# ===========================================

def notify(title, message):
    safe_title = title.replace('"', '\\"')
    safe_message = message.replace('"', '\\"')
    os.system(f'osascript -e \'display notification "{safe_message}" with title "{safe_title}"\'')

def create_rproj_file(project_root):
    """创建RStudio项目文件"""
    try:
        rproj_name = f"{project_root.name}.Rproj"
        rproj_path = project_root / rproj_name

        content = """Version: 1.0

RestoreWorkspace: Default
SaveWorkspace: Default
AlwaysSaveHistory: Default

EnableCodeIndexing: Yes
UseSpacesForTab: Yes
NumSpacesForTab: 2
Encoding: UTF-8

RnwWeave: Sweave
LaTeX: pdfLaTeX
"""
        if not rproj_path.exists():
            with open(rproj_path, 'w', encoding='utf-8') as f:
                f.write(content)
    except Exception:
        pass

def set_folder_view_settings(folder_path):
    """设置文件夹视图:列表、名称排序、展开"""
    try:
        p = str(folder_path.resolve())
        applescript = f'''
        tell application "Finder"
            try
                set target_folder to (POSIX file "{p}") as alias
                open target_folder
                tell container window of target_folder
                    set current view to list view
                    set sort column of list view options to name column
                    set sort direction of list view options to normal
                    try
                        set expanded of every folder of target_folder to true
                    end try
                end tell
                close container window of target_folder
            end try
        end tell
        '''
        subprocess.run(["osascript", "-e", applescript], check=False)
    except Exception:
        pass

def main():
    processed_count = 0

    for arg in sys.argv[1:]:
        target_root = Path(arg)

        # 确保是文件夹
        if not target_root.is_dir():
            target_root = target_root.parent

        try:
            # 步骤1: 创建文件夹结构
            for sub_path in STRUCTURE_LIST:
                full_path = target_root / sub_path
                full_path.mkdir(parents=True, exist_ok_ok=True)

            # 步骤2: 创建脚本模板
            templates_dir = target_root / "01_Scripts/00_Templates"
            if templates_dir.exists():
                for base_name in SCRIPT_BASENAMES:
                    for ext in [".py", ".R"]:
                        file_path = templates_dir / f"{base_name}{ext}"
                        if not file_path.exists():
                            file_path.touch()

            # 步骤3: 创建Rproj文件
            create_rproj_file(target_root)

            # 步骤4: 设置文件夹视图
            set_folder_view_settings(target_root)

            processed_count += 1

        except Exception as e:
            notify("创建出错", f"{target_root.name}: {str(e)}")

    if processed_count > 0:
        notify("项目初始化完成", f"已生成{processed_count}个项目的结构和模板")

if __name__ == "__main__":
    main()

EOF

📖 使用方法

  1. 在Finder中创建一个新文件夹,命名为你的项目名称(如"HFpEF_研究")
  2. 右键点击该文件夹,选择"快速操作""项目结构初始化"
  3. 等待系统通知提示"项目初始化完成"
  4. 双击生成的.Rproj文件,用RStudio打开项目
💡 使用技巧
  • 可以同时选中多个文件夹进行批量初始化
  • Templates中的脚本已包含常用分析流程的模板
  • 双击.Rproj文件可以直接用RStudio打开整个项目
  • 文件夹会自动以列表视图展示,按名称排序

🎨 自定义配置

你可以根据需要修改脚本中的配置:

修改目录结构

编辑STRUCTURE_LIST,添加或删除目录

修改脚本模板

编辑SCRIPT_BASENAMES,添加你常用的脚本名称

添加模板内容

create_rproj_file函数中修改Rproj配置