3.1 KiB
#!/usr/bin/env python3
-- coding: utf-8 --
import os import pandas as pd import re from pypinyin import lazy_pinyin
INPUT_DIR = "/Users/gavin/kman/export" OUTPUT_DIR = os.path.join(INPUT_DIR, "out") os.makedirs(OUTPUT_DIR, exist_ok=True)
def parse_filename(filename): """ 从文件名解析 title 和 subtitle note_bleafA:B-C.md -> title=A, subtitle=B 如果没有冒号,subtitle为空 """ base = os.path.basename(filename).replace("note_bleaf", "").rsplit("-", 1)[0].rsplit(".md", 1)[0] if ":" in base: title, subtitle = base.split(":", 1) else: title = base subtitle = "" return title.strip(), subtitle.strip()
def slugify(title): """ 中文转拼音,保留字母,长度不超过15 """ py = "".join(lazy_pinyin(title)) py = re.sub("[^a-zA-Z]", "", py) return py[:15]
def parse_content(filepath): """ 使用 pandas 读取 CSV 内容,跳过第二行分隔符 """ try: df = pd.read_csv(filepath, sep="|", engine="python", dtype=str, skiprows=[1]).dropna(how="all", axis=1) except Exception as e: print(f"❌ 解析失败 {filepath}: {e}") return pd.DataFrame()
# MARKTIME 转 datetime
if "MARKTIME" in df.columns:
df["MARKTIME"] = pd.to_datetime(df["MARKTIME"], errors="coerce")
else:
df["MARKTIME"] = pd.NaT
# AUTHOR 列保证存在
if "AUTHOR" not in df.columns:
df["AUTHOR"] = "未知"
return df
def convert_file(filepath): df = parse_content(filepath) if df.empty: return
title, subtitle = parse_filename(filepath)
slug = slugify(title)
author_name = df['AUTHOR'].iloc[0] if not df['AUTHOR'].isnull().all() else "未知"
# 最早的标记时间
if df['MARKTIME'].isnull().all():
date_str = "2025-01-07 11:00:00"
else:
date_str = df['MARKTIME'].min().strftime("%Y-%m-%d %H:%M:%S")
out_lines = [
"---",
f"title: '{title}'",
f"subtitle: '{subtitle}'",
f"author: 大童",
f"date: {date_str}",
f"slug: {slug}",
"description:",
"---",
f"作者:{author_name}",
""
]
# 处理正文
prev_hl = ""
for _, row in df.iterrows():
content = row.get("CONTENT", "")
if row.get("TYPE") == "HL":
out_lines.append(content)
out_lines.append("") # 空行
prev_hl = content
elif row.get("TYPE") == "NT":
out_lines.append(f"> {content}")
out_lines.append("") # 可选空行
else:
# 其他类型直接加内容
out_lines.append(content)
out_lines.append("")
output_filename = f"note_{title}.md"
output_path = os.path.join(OUTPUT_DIR, output_filename)
with open(output_path, "w", encoding="utf-8") as f:
f.write("\n".join(out_lines))
print(f"✅ 生成 {output_path}")
def main(): for fname in os.listdir(INPUT_DIR): if fname.startswith("note_bleaf") and fname.endswith(".md"): convert_file(os.path.join(INPUT_DIR, fname))
if name == "main": main()