import re
import os
#需求场景: 本人刚开始使用的Typora软件 这个软件的缺点就是 1 收费 2每次打开文件把截图放到md文件的时候 如果没选择偏好设置是设定的文件夹 就会导致截图默认存到c盘这样的后果就是文件如果转移到其他电脑 就会导致有些图片无法加载
#解决方法
# 1 如果不打算换掉Typora软件的话 就把原先的c盘地址的图片拷到自己设置图片路径的文件夹下面 然后使用第一个脚本 统一替换所有md文件图片的地址 生成新的md文件 但是这样治标不治本
# 2 用obsidian软件替代Typora软件 先把obsidian软件的md文件的图片地址统一设置成跟文件同级的assets文件夹下 具体怎么设置搜索一下 执行替换obsidian图片路径的代码 把原先的c盘地址的图片和其他路径的图片拷到自己设置ovsidian图片路径的assets文件夹下面 搞定 完美迁移
#md统一替换图片路径
def replace_image_paths1(md_file_path, new_directory, output_file_path):
# 读取Markdown文件内容
with open(md_file_path, 'r', encoding='utf-8') as file:
md_content = file.read()
# 使用正则表达式找到图片目录路径
pattern = re.compile(r'!\[.*\]\((.*?)\)')
matches = pattern.findall(md_content)
# 替换图片目录路径
for match in matches:
# 获取图片文件名
image_file_name = os.path.basename(match)
# 构建新的图片路径,并将正斜杠替换为反斜杠
new_path = os.path.join(new_directory, image_file_name).replace('/', '\\')
# 替换图片路径
md_content = md_content.replace(match, new_path)
# 写入新文件
with open(output_file_path, 'w', encoding='utf-8') as new_file:
new_file.write(md_content)
# 使用示例
md_file_path = 'D:/桌面/工作注意事项/new/0.md'
output_file_path = 'D:/桌面/工作注意事项/new/file.md'
new_directory = 'assets'
replace_image_paths1(md_file_path, new_directory, output_file_path)
#======================================================================================================================================================
#替换obsidian图片路径
def replace_image_paths(md_file_path, output_file_path):
# 读取Markdown文件内容
with open(md_file_path, 'r', encoding='utf-8') as file:
md_content = file.read()
# 使用正则表达式找到图片目录路径
pattern = re.compile(r'!\[.*?\]\(.*?\)')
matches = pattern.findall(md_content)
# 替换图片目录路径
for match in matches:
print(match)
# 获取图片文件名
image_file_name= os.path.basename(match).replace(")", "")
# 构建新的图片路径,并将正斜杠替换为反斜杠
new_path ='![['+image_file_name+']]'
print(new_path)
# # 替换图片路径
md_content = md_content.replace(match, new_path)
# 写入新文件
with open(output_file_path, 'w', encoding='utf-8') as new_file:
new_file.write(md_content)
# 使用示例
md_file_path = 'D:/桌面/工作注意事项/new/0.md'
output_file_path = 'D:/桌面/工作注意事项/new/file.md'
replace_image_paths(md_file_path, output_file_path)
04-24
1305
11-02