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
41
42
43
44
| import os
import re
import yaml
def modify_frontmatter(frontmatter, modifications):
frontmatter = frontmatter.copy()
for key, value in modifications.items():
if key == '_add':
frontmatter.update(value) # 添加键值对
elif key == '_delete':
for k in value:
frontmatter.pop(k, None) # 删除键
elif key in frontmatter:
if value['new_key'] is not None: # 修改键名
frontmatter[value['new_key']] = frontmatter.pop(key)
if value['new_value'] is not None: # 修改键值
frontmatter[key if value['new_key'] is None else value['new_key']] = value['new_value']
return frontmatter
def convert_frontmatter(folder_path, modifications):
for root, dirs, files in os.walk(folder_path):
for file in files:
if file.endswith('.md'):
file_path = os.path.join(root, file)
with open(file_path, 'r', encoding='utf8') as f:
content = f.read()
frontmatter_str = re.search(r'(?s)^---.*?---', content).group()
frontmatter = yaml.safe_load(frontmatter_str[3:-3])
modified_frontmatter = modify_frontmatter(frontmatter, modifications)
modified_frontmatter_str = yaml.dump(modified_frontmatter, allow_unicode=True)
content = re.sub(r'(?s)^---.*?---', r'---\n' + modified_frontmatter_str + r'---', content, count=1)
with open(file_path, 'w', encoding='utf8') as f:
f.write(content)
# 修改文件夹路径
folder_path = r"D:\GitHub\hexo-blog\source\_posts"
# 添加、删除、修改的键及其对应的值
modifications = {
'cover': {'new_key': 'index_img', 'new_value': None}, # 修改键名
# '_add': {'author': 'leon'}, # 添加新键
# '_add': {'tag': ['Python', 'Markdown']}, # 添加新键
# '_delete': ['math'], # 删除键
}
convert_frontmatter(folder_path, modifications)
|