63 lines
2.1 KiB
Python
63 lines
2.1 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
更新Markdown文件中的图片引用
|
|
将"下图"、"上图"、"图中"等文字引用替换为实际的图片链接
|
|
"""
|
|
|
|
import re
|
|
import os
|
|
|
|
def update_image_references(markdown_file, image_dir):
|
|
"""更新Markdown文件中的图片引用"""
|
|
|
|
# 读取Markdown文件
|
|
with open(markdown_file, 'r', encoding='utf-8') as f:
|
|
content = f.read()
|
|
|
|
# 获取图片文件列表
|
|
image_files = [f for f in os.listdir(image_dir) if f.endswith('.png')]
|
|
image_files.sort() # 按文件名排序
|
|
|
|
print(f"找到 {len(image_files)} 张图片")
|
|
|
|
# 先清理已有的图片引用(避免重复)
|
|
content = re.sub(r'!\[.*?\]\([^)]+\)', '', content)
|
|
|
|
# 图片引用模式 - 更精确的匹配
|
|
patterns = [
|
|
(r'(?<!!)\b下图\b', '![下图]'),
|
|
(r'(?<!!)\b上图\b', '![上图]'),
|
|
(r'(?<!!)\b图中\b', '![图中]'),
|
|
(r'(?<!!)\b此图\b', '![此图]'),
|
|
(r'(?<!!)\b该图\b', '![该图]'),
|
|
(r'(?<!!)\b图片\b', '![图片]'),
|
|
(r'(?<!!)\b图像\b', '![图像]'),
|
|
]
|
|
|
|
# 替换图片引用
|
|
image_index = 0
|
|
for pattern, replacement in patterns:
|
|
# 找到所有匹配的位置
|
|
matches = list(re.finditer(pattern, content))
|
|
|
|
for i, match in enumerate(matches):
|
|
if image_index < len(image_files):
|
|
# 替换为实际的图片链接
|
|
image_path = f"{image_dir}/{image_files[image_index]}"
|
|
new_reference = f"{replacement}({image_path})"
|
|
content = content.replace(match.group(), new_reference, 1)
|
|
image_index += 1
|
|
print(f"替换 '{match.group()}' -> '{new_reference}'")
|
|
|
|
# 保存更新后的文件
|
|
with open(markdown_file, 'w', encoding='utf-8') as f:
|
|
f.write(content)
|
|
|
|
print(f"更新完成,共替换了 {image_index} 个图片引用")
|
|
|
|
if __name__ == "__main__":
|
|
markdown_file = "/home/ben/code/huhan3000/converted/0_序_令人又敬又畏的_忽里勒台_大会.md"
|
|
image_dir = "/home/ben/code/huhan3000/images/0_序"
|
|
|
|
update_image_references(markdown_file, image_dir)
|