Skip to content

Instantly share code, notes, and snippets.

@capjamesg
Created July 11, 2021 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save capjamesg/fef6ba3deeb0290bd4707aa48bd98451 to your computer and use it in GitHub Desktop.
Save capjamesg/fef6ba3deeb0290bd4707aa48bd98451 to your computer and use it in GitHub Desktop.
This program converts ![]() markdown image syntax to an img tag with a u-photo microformats2 class.
import os
for filename in os.listdir("_posts/"):
if ".md" in filename:
with open("_posts/{}".format(filename), "r") as file:
line_number = 0
line_to_replace = ""
lines = list(file.readlines())
final_img_tag = ""
for l in lines:
line_number += 1
# Only search in first 10 lines because u-photo is for featured images and I kepe the featured image in the first 10 lines of my blog posts if I specify one
if line_number > 10:
break
if "![" in l:
# Get alt text and image URL
line_to_replace = l
find_last_square_bracket = l.find("]")
alt_text = l[2:find_last_square_bracket]
path = l[find_last_square_bracket+2:]
new_path = path.replace(")", "").replace("\n", "")
# Create new img tag
final_img_tag = '<img src="{}" alt="{}" class="u-photo">'.format(new_path, alt_text)
# Stop loop when the markdown image is found because I only want to replace one
break
new_file_content = ""
# Replace the line_to_replace (old markdown line) with the new img tag
for l in lines:
if l == line_to_replace:
new_line = l.replace(l, final_img_tag)
elif l != "\n":
new_line = l.replace("\n", "")
else:
new_line = l.strip()
new_file_content += new_line + "\n"
# Write amended file
writing_file = open("_posts/{}".format(filename), "w+")
writing_file.write(new_file_content)
writing_file.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment