去除md文件图片目录中不需要的图片

发布时间 2023-08-04 15:13:36作者: charonlight

首先,指定源目录,该目录应包含你要处理的Markdown文件和其对应的本地图片文件。
然后,指定结果目录,这是脚本将复制Markdown文件和图片到的目标位置。
脚本会遍历源目录中的所有Markdown文件,将它们复制到结果目录,并在结果目录中创建一个./typora-img/的子目录,用于存储Markdown文件中引用的本地图片。
对于每个Markdown文件,脚本会读取其中的本地图片路径,并将对应的本地图片复制到./typora-img/{filename}/目录下,其中{filename}是Markdown文件的名称(不包含后缀)。脚本还会更新Markdown文件中本地图片的引用路径,将其指向./typora-img/{filename}/目录下的图片。
如果Markdown文件中存在网络图片路径(以http://或https://开头),脚本将跳过它们,并在控制台输出相应的提示信息。

# md_image_copy.py

import os
import shutil
import re

def copy_md_files(src_dir, dest_dir):
    # 创建结果目录
    os.makedirs(dest_dir, exist_ok=True)

    # 获取所有md文件
    md_files = [f for f in os.listdir(src_dir) if f.endswith(".md")]

    for md_file in md_files:
        src_path = os.path.join(src_dir, md_file)
        dest_path = os.path.join(dest_dir, md_file)

        try:
            # 复制md文件到结果目录
            shutil.copy(src_path, dest_path)
            print(f"【提示】复制 {md_file} 到结果目录")

            # 获取md文件名(不带后缀)
            md_filename = os.path.splitext(md_file)[0]

            # 生成对应的图片目录
            img_dir = os.path.join(dest_dir, f"./typora-img/{md_filename}")
            os.makedirs(img_dir, exist_ok=True)
            print(f"【提示】创建图片目录 {img_dir}")

            # 读取md文件内容
            with open(dest_path, "r", encoding="utf-8") as file:
                content = file.read()

            # 匹配md中的本地图片地址
            local_img_pattern = r"!\[.*?\]\((.*?)\)"
            local_img_paths = re.findall(local_img_pattern, content)

            for img_path in local_img_paths:
                # 判断是否为网络图片地址
                if not img_path.startswith("http://") and not img_path.startswith("https://"):
                    # 复制图片到对应的目录
                    img_filename = os.path.basename(img_path)
                    img_src_path = os.path.join(src_dir, img_path)
                    img_dest_path = os.path.join(img_dir, img_filename)
                    shutil.copy(img_src_path, img_dest_path)
                    print(f"【提示】复制图片 {img_filename} 到目录 {img_dir}")

                    # 替换图片地址
                    new_img_path = f"./typora-img/{md_filename}/{img_filename}"
                    content = content.replace(img_path, new_img_path)
                else:
                    print(f"【!!!提示】跳过网络图片 {img_path}")

            # 更新md文件内容
            with open(dest_path, "w", encoding="utf-8") as file:
                file.write(content)

            print(f"【提示】更新 {md_file} 中的图片地址")

        except Exception as e:
            print(f"【!!!错误】处理 {md_file} 时出错:{e}")

if __name__ == "__main__":
    src_directory = "./"  # 将源目录设置为当前目录
    dest_directory = "./result"  # 替换为你的结果目录

    copy_md_files(src_directory, dest_directory)