Question:
Automatically add the absolute path of an image to mark

Problem:

I'm trying to convert markdown to restructured text. markdown has a picture with a relative path, how to automatically add an absolute path instead of a relative path?


This is my code


import m2r


def convert(md_file):

    with open(md_file, mode='r') as r_file:

        text = r_file.read()

    return m2r.convert(text=text)



Solution:

To automatically replace relative image paths with absolute paths in your Markdown content before converting it to reStructuredText, you can use regular expressions to search for the image syntax and replace the relative path with the absolute path. Here's an example of how you might modify your code to achieve this:


import re

import m2r


def convert(md_file, absolute_path_prefix):

    with open(md_file, mode='r') as r_file:

        text = r_file.read()


    img_pattern = re.compile(r'!\[(.*?)\]\((.*?)\)')


    def replacer(match):

        alt_text = match.group(1)

        rel_path = match.group(2)

        if rel_path.startswith('http://') or rel_path.startswith('https://') or rel_path.startswith('/'):

            return match.group(0)

        abs_path = absolute_path_prefix + rel_path

        return f'![{alt_text}]({abs_path})'


    text_with_abs_paths = img_pattern.sub(replacer, text)


    return m2r.convert(text=text_with_abs_paths)


md_file = 'example.md'

absolute_path_prefix = 'http://www.example.com/images/'  # Example absolute path

rst_content = convert(md_file, absolute_path_prefix)

print(rst_content)


This code opens a markdown file, searches for markdown image tags, and uses the replacer function to replace any relative paths with the specified absolute path, as long as they're not already absolute URLs or web links. After it updates the paths, it then converts the modified markdown content into reStructuredText using the m2r library.


Replace http://www.example.com/images/ with the actual absolute path you need for your images. This is a simple example and might need to be adjusted to fit the specific format of your paths or other requirements you might have. Hope it's helpful for you.


Suggested blogs:

>PHP cURL to upload video to azure blob storage

>PHP Error Solved: htaccess problem with an empty string in URL

>Plugins and Presets for Vuejs project

>Python Error Solved: load_associated_files do not load a txt file

>Python Error Solved: pg_config executable not found

>Set up Node.js & connect to a MongoDB Database Using Node.js

>Setting up a Cloud Composer environment: Step-by-step guide

>How to merge cells with HTML, CSS, and PHP?


Ritu Singh

Ritu Singh

Submit
0 Answers