本文目录导读:

我来介绍几种常见的方式来整理笔记,从简单到复杂:
Python 脚本(推荐)
基础整理脚本
import os
import shutil
from pathlib import Path
import re
from datetime import datetime
class NoteOrganizer:
def __init__(self, notes_dir):
self.notes_dir = Path(notes_dir)
def organize_by_date(self):
"""按日期整理笔记"""
for note in self.notes_dir.glob("*.md"):
# 从文件名提取日期 (假设格式: 2024-01-15-笔记名.md)
match = re.search(r'(\d{4}-\d{2}-\d{2})', note.stem)
if match:
date = match.group(1)
year_month = date[:7] # 2024-01
target_dir = self.notes_dir / year_month
target_dir.mkdir(exist_ok=True)
shutil.move(str(note), str(target_dir / note.name))
def organize_by_tags(self):
"""按标签整理笔记"""
for note in self.notes_dir.glob("*.md"):
tags = self.extract_tags(note)
for tag in tags:
target_dir = self.notes_dir / "tags" / tag
target_dir.mkdir(parents=True, exist_ok=True)
# 创建快捷方式或复制
shutil.copy2(str(note), str(target_dir / f"@{note.name}"))
def extract_tags(self, filepath):
"""从笔记中提取标签"""
tags = []
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
# 匹配 #标签 格式
tags = re.findall(r'#(\w+)', content)
return tags
def merge_similar_notes(self, keyword):
"""合并包含特定关键词的笔记"""
similar_notes = []
for note in self.notes_dir.glob("*.md"):
with open(note, 'r', encoding='utf-8') as f:
if keyword in f.read():
similar_notes.append(note)
if len(similar_notes) > 1:
# 创建合并文件
merged_path = self.notes_dir / f"merged_{keyword}.md"
with open(merged_path, 'w', encoding='utf-8') as merged:
merged.write(f"# {keyword} 的笔记合并\n\n")
for note in similar_notes:
merged.write(f"## 来源: {note.name}\n\n")
with open(note, 'r', encoding='utf-8') as f:
merged.write(f.read() + "\n\n---\n\n")
# 使用示例
if __name__ == "__main__":
organizer = NoteOrganizer("/path/to/notes")
organizer.organize_by_date()
organizer.organize_by_tags()
print("笔记整理完成!")
Shell 脚本(macOS/Linux)
简单整理脚本
#!/bin/bash
# 按日期组织笔记
organize_by_date() {
local notes_dir="$1"
cd "$notes_dir"
for note in *.md; do
# 提取日期
date_prefix=$(echo "$note" | grep -oP '\d{4}-\d{2}')
if [ -n "$date_prefix" ]; then
mkdir -p "$date_prefix"
mv "$note" "$date_prefix/"
fi
done
}
# 清理空目录
clean_empty_dirs() {
find "$1" -type d -empty -delete
}
# 按文件类型整理
organize_by_type() {
local target_dir="$1"
# 创建分类目录
mkdir -p "$target_dir"/{markdown,images,pdfs,others}
# 移动文件
mv "$target_dir"/*.md "$target_dir"/markdown/ 2>/dev/null
mv "$target_dir"/*.{png,jpg,gif} "$target_dir"/images/ 2>/dev/null
mv "$target_dir"/*.pdf "$target_dir"/pdfs/ 2>/dev/null
echo "文件整理完成!"
}
# 主函数
main() {
local notes_dir="${1:-./notes}"
echo "开始整理笔记目录: $notes_dir"
organize_by_date "$notes_dir"
clean_empty_dirs "$notes_dir"
echo "整理完成!"
}
main "$@"
高级功能脚本
带自动分类的智能整理
import os
import json
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.cluster import KMeans
import numpy as np
class SmartNoteOrganizer:
def __init__(self, notes_dir, categories_path=None):
self.notes_dir = notes_dir
self.categories = self.load_categories(categories_path)
def load_categories(self, path):
"""加载分类规则"""
if path and os.path.exists(path):
with open(path, 'r', encoding='utf-8') as f:
return json.load(f)
return {
"技术": ["python", "javascript", "代码", "算法"],
"生活": ["日记", "美食", "旅行", "健康"],
"工作": ["会议", "项目", "任务", "计划"],
"学习": ["课程", "笔记", "书籍", "论文"]
}
def auto_classify(self):
"""自动分类笔记"""
notes_content = []
note_paths = []
for note in self.notes_dir.glob("*.md"):
with open(note, 'r', encoding='utf-8') as f:
content = f.read()
notes_content.append(content)
note_paths.append(note)
if len(notes_content) < 2:
return
# 使用TF-IDF进行文本分析
vectorizer = TfidfVectorizer(max_features=100)
X = vectorizer.fit_transform(notes_content)
# K-means聚类
n_clusters = min(len(self.categories), len(notes_content))
kmeans = KMeans(n_clusters=n_clusters, random_state=42)
labels = kmeans.fit_predict(X)
# 移动笔记到对应分类目录
for note_path, label in zip(note_paths, labels):
category_name = list(self.categories.keys())[label]
target_dir = self.notes_dir / category_name
target_dir.mkdir(exist_ok=True)
# 如果笔记不在分类目录中
if note_path.parent != target_dir:
target_path = target_dir / note_path.name
# 处理重名文件
if target_path.exists():
base = note_path.stem
suffix = note_path.suffix
target_path = target_dir / f"{base}_{datetime.now().strftime('%H%M%S')}{suffix}"
shutil.move(str(note_path), str(target_path))
def generate_summary(self):
"""生成笔记摘要/索引"""
summary = {}
for note in self.notes_dir.glob("**/*.md"):
category = note.parent.name
if category not in summary:
summary[category] = []
summary[category].append({
"name": note.name,
"size": note.stat().st_size,
"modified": datetime.fromtimestamp(note.stat().st_mtime).isoformat()
})
# 生成索引文件
index_path = self.notes_dir / "_index.md"
with open(index_path, 'w', encoding='utf-8') as f:
f.write("# 笔记索引\n\n")
for category, notes in summary.items():
f.write(f"## {category}\n")
for note in notes:
f.write(f"- [{note['name']}]({category}/{note['name']}) - {note['modified']}\n")
f.write("\n")
# 使用示例
organizer = SmartNoteOrganizer("/path/to/notes")
organizer.auto_classify()
organizer.generate_summary()
配合 Obsidian 的脚本
# obsidian_organizer.py
import json
from pathlib import Path
class ObsidianOrganizer:
def __init__(self, vault_path):
self.vault = Path(vault_path)
def fix_links(self):
"""修复 Obsidian 笔记链接"""
for note in self.vault.glob("**/*.md"):
content = note.read_text(encoding='utf-8')
# 修复图片路径
content = content.replace("![[./", "![[")
# 确保链接格式正确
# 将 [[链接|显示文本]] 标准化
import re
content = re.sub(
r'\[\[([^|]+)\|([^\]]+)\]\]',
lambda m: f'[[{m.group(1).strip()}|{m.group(2).strip()}]]',
content
)
note.write_text(content, encoding='utf-8')
def organize_by_metadata(self):
"""根据 YAML front matter 整理笔记"""
for note in self.vault.glob("**/*.md"):
content = note.read_text(encoding='utf-8')
# 提取 YAML front matter
if content.startswith('---'):
end = content.find('---', 3)
if end != -1:
front_matter = content[3:end]
metadata = {}
for line in front_matter.split('\n'):
if ':' in line:
key, value = line.split(':', 1)
metadata[key.strip()] = value.strip()
# 根据标签整理
if 'tags' in metadata:
tags = [t.strip() for t in metadata['tags'].split(',')]
for tag in tags:
tag_dir = self.vault / 'tags' / tag
tag_dir.mkdir(parents=True, exist_ok=True)
# 创建或更新笔记在标签目录的链接
link_path = tag_dir / note.name
if not link_path.exists():
link_path.symlink_to(note)
# 使用
organizer = ObsidianOrganizer("/path/to/obsidian/vault")
organizer.fix_links()
定时执行
使用 cron(Linux/macOS)
# 每天凌晨2点整理笔记 0 2 * * * /usr/bin/python3 /path/to/note_organizer.py # 每周一早上8点整理 0 8 * * 1 /path/to/organize_notes.sh /home/user/notes
使用 Task Scheduler(Windows)
# PowerShell 创建定时任务 $action = New-ScheduledTaskAction -Execute "python.exe" -Argument "D:\scripts\note_organizer.py" $trigger = New-ScheduledTaskTrigger -Daily -At 2am Register-ScheduledTask -TaskName "OrganizeNotes" -Action $action -Trigger $trigger
使用建议
- 先备份:运行脚本前确保有笔记备份
- 逐步执行:先在测试目录运行
- 定制规则:根据你的笔记习惯修改脚本
- 添加日志:记录每次整理的内容
需要哪种特定功能的脚本,或者想针对某个笔记软件优化,我可以帮你进一步调整!