#!/usr/bin/env python3 """ 生成图文混排的 HTML(图片内联为 base64),方便直接复制 """ import os import re import base64 BASE_DIR = "/root/openclaw-workspace/projects/yu-zhi-ran/content/published/2026-04-14-上海阳台种菜一年" MD_FILE = os.path.join(BASE_DIR, "final-article.md") IMAGES_DIR = os.path.join(BASE_DIR, "images") # 使用发布目录内的 images OUT_HTML = os.path.join(BASE_DIR, "上海阳台种菜一年_内联.html") # 读取 Markdown with open(MD_FILE, "r", encoding="utf-8") as f: content = f.read() # 预加载图片并转为 base64 image_cache = {} for fname in os.listdir(IMAGES_DIR): if fname.endswith('.png'): path = os.path.join(IMAGES_DIR, fname) with open(path, "rb") as imgf: b64 = base64.b64encode(imgf.read()).decode('utf-8') image_cache[fname] = b64 # 替换图片 def replace_img(match): alt = match.group(1) fname = match.group(2) key = os.path.basename(fname) if key in image_cache: return f'{alt}' else: return f'

[图片缺失: {fname}]

' content = re.sub(r'!\[(.*?)\]\((images/.*?)\)', replace_img, content) # Markdown 转 HTML html_lines = [] for line in content.split('\n'): if line.startswith('# '): html_lines.append(f'

{line[2:]}

') elif line.startswith('## '): html_lines.append(f'

{line[3:]}

') elif line.startswith('### '): html_lines.append(f'

{line[4:]}

') elif line.startswith('---'): html_lines.append('
') elif line.startswith('> '): html_lines.append(f'
{line[2:]}
') elif re.match(r'^[-*] ', line): html_lines.append(f'
  • {line[2:]}
  • ') elif re.match(r'^\d+\. ', line): html_lines.append(f'
  • {line[line.find(". ")+2:]}
  • ') elif line.strip() == '': html_lines.append('
    ') else: tmp = re.sub(r'\*\*(.*?)\*\*', r'\1', line) tmp = re.sub(r'\*(.*?)\*', r'\1', tmp) html_lines.append(f'

    {tmp}

    ') html = f''' 上海阳台种菜一年 {chr(10).join(html_lines)} ''' with open(OUT_HTML, "w", encoding="utf-8") as f: f.write(html) print(f"✅ HTML 已生成: {OUT_HTML}") print(f"📊 字符数: {len(content)}") print(f"🖼️ 内嵌图片: {len(image_cache)} 张")