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
| import os import re
def add_cover_property(file_path): with open(file_path, 'r', encoding='utf-8') as file: content = file.read()
cover_match = re.search(r'!\[\[Pasted image \d+\.png\]\]', content) if cover_match: cover_content = cover_match.group(0) else: print(f"No matching 'Pasted image' found in {file_path}") return
yaml_header_match = re.match(r'^---\n(.*?)\n---\n(.*)', content, re.DOTALL)
if yaml_header_match: yaml_header, body = yaml_header_match.groups() if not re.search(r'^cover:', yaml_header, re.MULTILINE): yaml_header += f'\ncover: "{cover_content}"\n' else: yaml_header = re.sub(r'^cover:.*$', f'cover: "{cover_content}"', yaml_header, flags=re.MULTILINE) new_content = f'---\n{yaml_header}\n---\n{body}' else: new_content = f'---\ncover: "{cover_content}"\n---\n{content}'
with open(file_path, 'w', encoding='utf-8') as file: file.write(new_content)
print(f'Processed {file_path}')
def process_markdown_files(root_dir): for dirpath, _, filenames in os.walk(root_dir): for filename in filenames: if filename.endswith('.md'): file_path = os.path.join(dirpath, filename) add_cover_property(file_path)
root_directory = r'自定义目录' process_markdown_files(root_directory)
|