add_alt_text.py
· 1.2 KiB · Python
Originalformat
import os
import re
import sys
def add_alt_text_to_images(directory):
md_files = [f for f in os.listdir(directory) if f.endswith((".md", ".mdx"))]
image_pattern = re.compile(r'!\[([^\]]*)\]\(([^\)]+)\)')
for md_file in md_files:
md_path = os.path.join(directory, md_file)
with open(md_path, "r", encoding="utf-8") as file:
content = file.read()
def replace_alt(match):
alt_text, image_path = match.groups()
if alt_text.strip():
return match.group(0)
image_name = os.path.basename(image_path)
alt_text = os.path.splitext(image_name)[0].replace("_", " ").replace("-", " ")
return f''
new_content = image_pattern.sub(replace_alt, content)
with open(md_path, "w", encoding="utf-8") as file:
file.write(new_content)
print(f"Processed: {md_file}")
if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: python script.py <directory>")
sys.exit(1)
directory = sys.argv[1]
if not os.path.isdir(directory):
print("Error: Directory does not exist.")
sys.exit(1)
add_alt_text_to_images(directory)
| 1 | import os |
| 2 | import re |
| 3 | import sys |
| 4 | |
| 5 | def add_alt_text_to_images(directory): |
| 6 | md_files = [f for f in os.listdir(directory) if f.endswith((".md", ".mdx"))] |
| 7 | image_pattern = re.compile(r'!\[([^\]]*)\]\(([^\)]+)\)') |
| 8 | |
| 9 | for md_file in md_files: |
| 10 | md_path = os.path.join(directory, md_file) |
| 11 | with open(md_path, "r", encoding="utf-8") as file: |
| 12 | content = file.read() |
| 13 | |
| 14 | def replace_alt(match): |
| 15 | alt_text, image_path = match.groups() |
| 16 | if alt_text.strip(): |
| 17 | return match.group(0) |
| 18 | |
| 19 | image_name = os.path.basename(image_path) |
| 20 | alt_text = os.path.splitext(image_name)[0].replace("_", " ").replace("-", " ") |
| 21 | return f'' |
| 22 | |
| 23 | new_content = image_pattern.sub(replace_alt, content) |
| 24 | |
| 25 | with open(md_path, "w", encoding="utf-8") as file: |
| 26 | file.write(new_content) |
| 27 | |
| 28 | print(f"Processed: {md_file}") |
| 29 | |
| 30 | if __name__ == "__main__": |
| 31 | if len(sys.argv) != 2: |
| 32 | print("Usage: python script.py <directory>") |
| 33 | sys.exit(1) |
| 34 | |
| 35 | directory = sys.argv[1] |
| 36 | if not os.path.isdir(directory): |
| 37 | print("Error: Directory does not exist.") |
| 38 | sys.exit(1) |
| 39 | |
| 40 | add_alt_text_to_images(directory) |