技术CDNPythonMarkdown 内部引用图片的链接替换脚本
Kitholt Frank孩子们,我回来了
哈哈嗨,时隔两年多,我再一次敲着键盘来码博客了。前几天换了服务器,我把很多服务和应用都搬到新的服务器了,其中就包括我的博客。在搬迁的过程中,我发现CDN—jsdelivr 似乎“挂了”,他只有在我挂梯子的时候才会“活过来”。我谷歌了一下,果然是我太久没联网了。这玩儿意早在 2022 年就已经给毙了。。。没办法,我现在只好使用小马哥的 COS,好在价格不贵,一年10G 容量也就 9.9,还能接受。存储桶已经买了,图片也都放在 COS 上了。现在最关键的就是。。。怎么把我 Markdown 里面的 所有 CDN 链接都换成现在的!几百张图片要我一张一张换,我是会🐭的(renzhen
仔细想想,我可以写一个简单的脚本来解决这个问题。链接替换的本质就是正则匹配,然后在匹配前有需要找出所有 后缀为 md 的文件。也就是说应该有两个核心方法:
- traverse_directory(directory)
- replace_image_links(md_file_paths, old_url, new_url)
traverse_directory方法接收一个指定目录,返回这个目录下的所有 md 文件
replace_image_links接收一个文件路径组成的数组,要替换的旧 url 部分,以及新的 url 部分
话不多说,直接上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
| import re import os
def traverse_directory(directory): file_paths = [] for root, dirs, files in os.walk(directory): for file in files: if file.endswith('.md'): file_path = os.path.join(root, file) file_paths.append(file_path) return file_paths
md_file_paths = traverse_directory('Desktop/Demo/files') print(md_file_paths)
def replace_image_links(md_file_paths, old_url, new_url): for file_path in md_file_paths: with open(file_path, 'r', encoding='utf-8') as file: content = file.read() pattern = r'!\[.*?\]\((.*?)\)' urls = re.findall(pattern, content) for url in urls: if old_url in url: temp_url = url.replace(old_url, new_url) content = content.replace(url, temp_url) with open(file_path, 'w', encoding='utf-8') as file: file.write(content)
replace_image_links(md_file_paths, 'https://cdn.jsdelivr.net/gh/kitholt/cdn', 'https://blog-resources-1301830793.cos.ap-hongkong.myqcloud.com')
|