首页 > 编程语言 >python脚本实现将md文件中的图片替换为本地存储

python脚本实现将md文件中的图片替换为本地存储

时间:2023-07-01 13:01:11浏览次数:49  
标签:md 存储 img python url file path local

实现将md文件中的网络图片下载下来,保存到本地./typora-img/{filename}目录,并且会将md文件中的图片地址替换为本地地址

# 代码参考:https://blog.csdn.net/weixin_34090643/article/details/91435765
import requests
import re
import os
from itertools import chain
import fnmatch


def get_md_files(path="./"):
    md_files = []
    for root_dir, dirs, files in os.walk(path):
        for file in files:
            if fnmatch.fnmatch(file, "*.md"):
                file_path = os.path.join(root_dir, file)
                md_files.append(os.path.relpath(file_path, path).replace("\\", "/"))
    return md_files


# 替换md文件中的url
def replace_md_url(md_file, local_img_path):
    img_patten = r'!\[.*?\]\((.*?)\)|<img.*?src=[\'\"](.*?)[\'\"].*?>'  # Markdown中图片语法 ![](url) 或者 <img src='' />
    cnt_replace = 0
    with open(md_file, 'r', encoding='utf-8') as f:
        post = f.read()
        matches = re.compile(img_patten).findall(post)
        if matches and len(matches) > 0:
            # 多个group整合成一个列表
            for match in list(chain(*matches)):
                if match != "":
                    new_url = download_image(match, local_img_path)  # 下载图片,返回图片路径
                    if new_url != False:  # 确保只有图片下载成功了才会去替换url
                        post = post.replace(match, new_url)
                        cnt_replace = cnt_replace + 1  # 统计需要替换的url数量
                        # 如果有内容的话,就直接覆盖写入当前的markdown文件
                        if post and cnt_replace > 0:
                            open(md_file, 'w', encoding='utf-8').write(post)
                            print(f"已更新{cnt_replace}个url")
                        elif cnt_replace == 0:
                            print('{}中没有需要替换的URL'.format(os.path.basename(md_file)))


# 获取到图片的保存的相对路径
def get_img_local_path(md_file, path):
    # /a/b/c
    if path.startswith('/'):
        local_img_path = path
    # ./a/b/c
    elif path.startswith('.'):
        local_img_path = '{0}/{1}'.format(os.path.dirname(md_file), path)
    # file:///a/b/c
    elif path.startswith('file:///'):
        local_img_path = path[8:]
        local_img_path = local_img_path.replace('%20', ' ')
    else:
        local_img_path = '{0}/{1}'.format(os.path.dirname(md_file), path)

    return local_img_path


# 下载图片
def download_image(image_url, save_dir):
    os.makedirs(save_dir, exist_ok=True)
    if not image_url.startswith('http://') or image_url.startswith('https://'):
        return False
    try:
        response = requests.get(image_url, stream=True)
        if response.status_code == 200:
            file_name = image_url.split("/")[-1]
            file_path = os.path.join(save_dir, file_name)
            with open(file_path, "wb") as file:
                for chunk in response.iter_content(1024):
                    file.write(chunk)
            print(f"{image_url}  --->图片爬取成功,已保存到{save_dir}")

            local_img_url = f"./{path}/{file_name}"
            return local_img_url

    except:
        print(f"{image_url}  --->图片爬取失败,!!!!!!!!")
        return False


if __name__ == '__main__':
    md_files = get_md_files()  # 可指定路径

    for md_file in md_files:
        md_name = md_file.split("/")[-1].split(".")[0]  # md文件名
        path = f'typora-img/{md_name}'

        local_img_path = get_img_local_path(md_file, path)  # 图片保存的相对路径
        replace_md_url(md_file, local_img_path)

标签:md,存储,img,python,url,file,path,local
From: https://www.cnblogs.com/charonlight/p/17519139.html

相关文章

  • 使用python paramiko模块将本地文件上传到远程主机的指定目录
    使用python paramiko模块将本地文件上传到远程主机的指定目录这个代码首先定义了本地文件名和远程文件名,然后使用datetime模块获取当前日期和时间,并使用字符串格式化功能生成了远程目录和文件名。在这个示例中,远程目录是/path/to/remote/directory/年份/月份/日期/,文件名是小时-......
  • 使用python生成随机密码
    使用python生成随机密码,密码长度13位,一般密码文件不能以?和!开头的,需要将这两个开头的密码文件排除掉。有两种方式。第一种方式importrandomimportstring#定义密码长度password_length=13#定义密码字符集合password_characters=string.ascii_letters+string.d......
  • 靳宇灵 | CHATGPT真的很强大,很快帮我解决了tp5对接腾讯cos存储的SDK,NB!!
    php请求腾讯云cos存储SDK报错ThrowableErrorinClient.phpline229致命错误:CalltoundefinedfunctionCos\region_map()这个错误的原因是您在使用腾讯云cos存储SDK时,调用了一个未定义的函数 Cos\region_map()。首先,您需要确保安装了腾讯云cos存储SDK。可以通过Composer进......
  • Python-练脑系列-04依旧是数据结构
    前言......
  • 面向对象编程Python:类、对象和继承
    面向对象编程(Object-OrientedProgramming,简称OOP)是一种常用的编程范式,它将数据和操作数据的函数封装在一起,以创建对象。Python是一种支持面向对象编程的高级编程语言,它提供了类(class)、对象(object)和继承(inheritance)等概念,使得代码更加模块化、可维护性更高。本文将介绍Python中的......
  • python执行终端命令并获得输出结果
    兼容windows和linux的终端执行函数defshell_exec(cmd:str)->str:  """ 执行终端命令,输出终端打印结果 :paramcmd: :return: """  withos.popen(cmd)asfp:    bf=fp._stream.buffer.read()  out=bf.decode().strip()  retu......
  • 16.python-单例模式
    python-单例模式单例模式适用于需要共享对象的场景单例模式,也叫单子模式,是一种常用的软件设计模式。在应用这个模式时,单例对象的类必须保证只有一个实例存在。许多时候整个系统只需要拥有一个的全局对象,这样有利于我们协调系统整体的行为。比如在某个服务器程序中,该服务器的配......
  • windows的cmd批处理命令及powershell (二)
    1、变量设置for/l%%iin(1,1,100)do@echo%%iset/ai=500set/ai=%i%+200echo%i%pause++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@echooffSETLOCALENABLEDELAYEDEXPANSIONfor/l%%iin(1110)do(set/avar=%%i+2echo!var!......
  • cmd批处理命令及powershell
    Powershell查询IP地址及主机名信息:1.foreach($ipv4 in (ipconfig) -like '*IPv4*') { ($ipv4 -split ' : ')[-1]}2.Get-WMIObject Win32_ComputerSystem |select Name3.$env:COMPUTERNAME4[net.dns]::GetHostAddresses('')|select-ExpandPropertyIPA......
  • python类与对象
    在Python中,类是一种用于创建对象的蓝图或模板。它们定义了对象的属性和方法。对象是类的实例化,它们是具体的、实际存在的实体。要定义一个类,可以使用class关键字,后面跟着类的名称。类名称通常使用首字母大写的驼峰命名法。下面是一个简单的类的示例:classPerson:def__init__(......