-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfixtitle.py
More file actions
70 lines (51 loc) · 2.71 KB
/
fixtitle.py
File metadata and controls
70 lines (51 loc) · 2.71 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import os
import re
def replace_headers_in_md_files(directory):
# 使用 os.walk 递归遍历所有子目录和文件
for root, dirs, files in os.walk(directory):
for filename in files:
if filename.endswith(".md"):
filepath = os.path.join(root, filename)
with open(filepath, 'r', encoding='utf-8') as file:
content = file.read()
# 使用正则表达式匹配以 # 开头的行
new_content = re.sub(r'^# (.+)$', r'+++\ntitle = "\1"\n+++', content, flags=re.MULTILINE)
# 写回文件
with open(filepath, 'w', encoding='utf-8') as file:
file.write(new_content)
print(f"Processed {filepath}")
def rename_md_files_by_title(directory):
# 使用 os.walk 递归遍历所有子目录和文件
for root, dirs, files in os.walk(directory):
for filename in files:
if filename.endswith(".md") and not filename.startswith("index") and not filename.startswith("_index"):
filepath = os.path.join(root, filename)
with open(filepath, 'r', encoding='utf-8') as file:
content = file.read()
# 查找文件中的 title
title_match = re.search(r'\+\+\+\s*title\s*=\s*"([^"]+)"\s*\+\+\+', content)
if title_match:
title = title_match.group(1).strip() # 提取标题内容
new_filename = f"{title}.md"
new_filepath = os.path.join(root, new_filename)
# 重命名文件
os.rename(filepath, new_filepath)
print(f"Renamed '{filename}' to '{new_filename}'")
else:
print(f"No title found in '{filename}'")
def fill__index(directory):
# 使用 os.walk 递归遍历所有子目录和文件
for root, dirs, files in os.walk(directory):
for filename in files:
if filename.endswith(".md") and filename.startswith("_index"):
filepath = os.path.join(root, filename)
with open(filepath, 'r', encoding='utf-8') as file:
content = file.read()
content = content + '''\n\n{{% children depth="999" showhidden="true" %}}\n'''
# 写回文件
with open(filepath, 'w', encoding='utf-8') as file:
file.write(content)
target_directory = 'content'
# fill__index(target_directory)
# rename_md_files_by_title(target_directory)
# replace_headers_in_md_files(target_directory)