日常生活的交流与学习

首页 新随笔 联系 管理

convert markdown 2 code project by python

import os
import re
import sys


def create_from_file_path(base_dir, file_path, content):
    # Create the full directory path
    dir_path = os.path.join(base_dir, os.path.dirname(file_path))
    # Create the directories if they don't exist
    os.makedirs(dir_path, exist_ok=True)
    # Create the full file path
    full_file_path = os.path.join(base_dir, file_path)
    # Create the file
    with open(full_file_path, "w", encoding="utf-8") as f:
        f.write(content)
        f.close()


def get_root_path(path):
    dir_path = path
    # 判断当前文件是否是文件
    if os.path.isfile(path):
        dir_path = os.path.dirname(path)
    return dir_path


if __name__ == "__main__":
    md_file_path = sys.argv[1]
    base_dir = get_root_path(md_file_path)

    with open(md_file_path, "r", encoding="utf-8") as f:  # 打开文件
        md_text = f.read()
        # Match the first-level headings and code blocks
        # \n{1,}# `(.+)`\n{1,}```\w{2,5}\n{1,}
        pattern = r"^# `(.+)`\n{1,}```(?:\w{2,}\n)([\s\S]+?)\n{1,}```\n{1,}"
        matches = re.findall(pattern, md_text, re.MULTILINE)

        # Loop over the matches
        for i, (file_path, code) in enumerate(matches):
            print(f"{i}->", file_path)
            create_from_file_path(base_dir, file_path, code)

        print(f"=============done_{len(matches)}=============")
        f.close()

posted on 2024-01-17 07:09  lazycookie  阅读(6)  评论(0编辑  收藏  举报