popyone
发布于 2024-07-07 / 7 阅读
0
0

joplin数据导入obsidian的预处理脚本

​ 昨天joplin 安卓app升级到3.0.8,无法使用s3同步数据,遂转到obsidian,功能上将后者比前者丰富,读取原生markdown比joplin的格式方便,同步使用第三方s3插件remotely save,编辑代码使用vscode editor插件,手机端插件通用(复制整个数据目录到手机,导入obsidian就能使用)。

​ 这里是将joplin奇怪的图像格式转成标准markdown格式的python脚本,通过百度AI生成,人工合成,包含三个功能:

  1. 将<ins><img>标签的图片转成markdown图片'![xxx](xxxx.png)'格式。
  2. 给'![xxx](xxxx)'不带扩展名的图片添加扩展名:'![xxx](xxxx.png)'。
  3. 在处理1和2的时候,给_resources目录下的图片添加上扩展名png。
import os
import re


def html_img_to_markdown(file_path):
    """
    修改html图片为markdown图片格式。
    """
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()

    # 使用正则表达式查找<ins>内的<img>标签,并转换为Markdown图像链接
    # 注意:这里假设src属性中的URL不包含查询字符串或锚点,且我们想要为图像添加一个默认的.png扩展名
    # 如果图像可能有不同的扩展名,你可能需要调整正则表达式来捕获并保留这些扩展名
    pattern1 = r'<ins>\s*<img\s+[^>]*?src="([^"]+)"[^>]*?>\s*</ins>'

    replacement = r'![]({0}.png)'.format(r'\1')  # 使用捕获组\1来引用src属性的值,并添加.png扩展名
    modified_content = re.sub(pattern1, replacement, content, flags=re.IGNORECASE)

    # 正则表达式匹配src属性中的图片名(不包括路径和扩展名)
    image_name_pattern = re.compile(r'src="([^"]*/)([^"]+)"')

    # 查找匹配项
    match = image_name_pattern.search(content)

    if match:
        # 提取路径和图片名(不包括路径)
        path, image_name = match.groups()

        # 原始图片路径
        old_src_path = f'{resources_root_directory}/{image_name}'
        print("老的src路径:", old_src_path)

        # 检查文件是否存在且没有.png扩展名
        if os.path.exists(old_src_path) and not old_src_path.endswith('.png .git .jpg'):
            # 添加.png扩展名
            new_image_path = old_src_path + '.png'
            os.rename(old_src_path, new_image_path)

        # 写回修改后的Markdown文件
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(modified_content)


def modify_markdown_paths(file_path):
    """
    修改Markdown文件中的路径。
    """
    with open(file_path, 'r', encoding='utf-8') as file:
        content = file.read()

    # 匹配并替换Markdown中的路径
    pattern1 = r'\((?P<prefix>(?:../)*)(?P<resource_dir>_resources/)(?P<filename>[\w-]+)\)'
    replacement = lambda match: f'({match.group("prefix")}{match.group("resource_dir")}{match.group("filename")}.png)'
    modified_content = re.sub(pattern1, replacement, content)

    # 正则表达式匹配图片链接
    image_pattern = re.compile(r'!\[.*?\]\((.*?)\)')
    matches = image_pattern.findall(content)

    # 遍历匹配到的图片链接
    for match in matches:
        # 去除路径中的任何可能存在的引号或空格
        cleaned_match = match.strip('" ').strip("'")
        cleaned_match = cleaned_match.split('/')[-1].split('.')[0]

        # 构建完整的图片文件路径
        image_path = os.path.join(resources_root_directory, cleaned_match)
        print(f'老的文件完整路径:{image_path}')

        # 检查文件是否存在且没有.png扩展名
        if os.path.exists(image_path) and not image_path.endswith('.png .git .jpg'):
            # 添加.png扩展名
            new_image_path = image_path + '.png'
            os.rename(image_path, new_image_path)

    # 写回修改后的Markdown文件
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(modified_content)


def find_and_modify_markdown_files(markdown_dir):
    """
    遍历Markdown文件并修改路径。
    """
    for root, dirs, files in os.walk(markdown_dir):
        for file in files:
            if file.endswith('.md'):
                file_path = os.path.join(root, file)
                print(f"Modifying Markdown file: {file_path}")
                modify_markdown_paths(file_path)
                html_img_to_markdown(file_path)


# 设置Markdown文件和_resources目录的根目录
markdown_root_directory = './'  # markdown目录
resources_root_directory = './_resources'  # 如果_resources就在markdown目录内,则可能相同

# 修改Markdown文件
find_and_modify_markdown_files(markdown_root_directory)



评论