一、前言

昨天部署Qexo后台时,把之前安排为图床的域名给错用(😀该死呀!)。本来是打算把后台的域名给换掉的,后来想像好久没用过正则表达式了,所以借此机会编写一个读取所有.md文件然后替换文章中原域名的Python短代码。

二、正文

具体代码如下,详细注释都写在代码里面了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import re
import os
# 读取.md文件并替换链接
def replace_links(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()

# 使用正则表达式找到包含'https://blog.gan1ser.top'的链接
pattern = r"(https://blog\.gan1ser\.top)(/.*)"
replaced_content = re.sub(pattern, r'https://pic.gan1ser.top\2', content)

# 将替换后的内容写回文件
with open(file_path, 'w', encoding='utf-8') as file:
file.write(replaced_content)

# 替换指定目录下的所有.md文件
def replace_links_in_directory(directory):
for file in os.listdir(directory):
if file.endswith(".md"):
file_path = os.path.join(directory, file)
replace_links(file_path)

# 使用示例
replace_links_in_directory('D:/Blog/blog\source/_posts')

比较简单,只能说正则太好用了