美文网首页移动开发
批量替换markdown本地图片地址为七牛外链

批量替换markdown本地图片地址为七牛外链

作者: huluo666 | 来源:发表于2019-01-21 18:53 被阅读7次

    平时用markdown写文章,直接截图粘贴非常快速,可要把本地的图片地址换成在线的,如果链接多了一一替换就比较麻烦了,所以直接用脚本批量替换,省时省力。

    ![image-20190121181601006](/Users/apple10/Library/Application Support/typora-user-images/image-20190121181601006.png)
    
    安装七牛Python库,命令行神器 Click
    • 直接安装:
    pip install qiniu
    pip install click
    或
    easy_install qiniu
    easy_install click
    

    QiniuUploader.py

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # Created by luo.h on 2019/1/18
    
    import os
    import re
    import click
    from qiniu import Auth, put_file, etag
    import qiniu.config
    
    
    #需要填写你的 Access Key 和 Secret Key
    access_key = 'lvmGUbLhnG1hXxxxxxxxxxxx'
    secret_key = 'sXFURu-EThOUosoC79OpE5ZDxxxxxxxx'
    #外链域名
    qiniu_domain = 'http://melo.awm4.cn/'
    #要上传的空间
    bucket_name = 'hlmd'
    #======需要修改以上信息============#
    
    class  QiniuUpload:
        def __init__(self,file_path):
            (filepath,tempfilename) = os.path.split(file_path)
            (filename,extension) = os.path.splitext(tempfilename)
            #构建鉴权对象
            q = Auth(access_key, secret_key)
            #上传到七牛后保存的文件名
            key = tempfilename
            #生成上传 Token,可以指定过期时间等
            token = q.upload_token(bucket_name, key,3600*7)
            #要上传文件的本地路径
            localfile = file_path
    #       print(localfile)
            ret, info = put_file(token, key, localfile)
    #       print(info)
            assert ret['key'] == key
            assert ret['hash'] == etag(localfile)
            self.key= ret['key']
            self.etag= ret['hash']
            self.cloudfile= qiniu_domain+ret['key']
    
    
    #读取文件
    def readContentInFile(filepath):
        with open(filepath, 'r') as f:  
    #       contents = f.readlines()
            contents = f.read()
        return contents
        
    
    def getURLsInFile(filePath):
        content = readContentInFile(filePath)   
        regex = r'!\[.+?\]\((.+?)\)' 
        results = re.findall(regex,content)
        return results
    
    
    def listdir_nohidden(path):
        return glob.glob(os.path.join(path, '*'))
        
    #file_Path 文件路径
    #uploadQiniu 是否上传七牛
    def scanFilesInRootPath(file_Path,uploadQiniu=False):
        urlDict={}
        for root, dirs, files in os.walk(file_Path):
            for file in files:
                (filename, extension) = os.path.splitext(file)
                # 原文件的路径
                old_path = os.path.join(root,file)
                if os.path.isfile(old_path) and extension==".md":
                    urls=getURLsInFile(old_path)
                    if len(urls)>0:
                        urlDict[old_path]=urls
        for key, value in urlDict.items():
            click.secho(key, fg='cyan', underline=True)
            for item in urlDict[key]:
                click.secho(item, fg='red', underline=True)
                if uploadQiniu==True:
                    #上传七牛
                    qiniu=QiniuUpload(item)
                    click.secho(qiniu.cloudfile,fg='red', underline=True)
                    replaceAllsubStrInFile(key,item, qiniu.cloudfile)
                else:
                    if item.startswith("http")==True:
                        print("✅已是线上地址")
                    else:
                        print("⚠️未允许上传到七牛")
    
        
    def replaceAllsubStrInFile(filePath,oldStr,newStr):
        aFile= open(filePath,'r') #打开所有文件
        str = aFile.read()
        aFile.close()
        str = str.replace(oldStr,newStr) #将字符串里前面全部替换为后面
        bFile = open(filePath,'w')
        bFile.write(str) #再写入
        bFile.close()#关闭文件
    
    if __name__ == '__main__':
        inputRootPath=input("请输入需要含有markdown文档的文件夹路径:")
        #qiniu=QiniuUpload("/Users/apple10/Documents/1024x1024.png")
        #print("返回结果:%s %s %s" %(qiniu.key,qiniu.etag,qiniu.cloudfile))
        #False 只打印本地图片地址,True 将本地图片上传至七牛并替换成七牛外链 
        scanFilesInRootPath(inputRootPath,False)
    

    使用步骤

    1、修改Access KeySecret Key等配置信息,如需上传本地图片并替换为七牛修改入口为scanFilesInRootPath(inputRootPath,True)

    2、运行python3 QiniuUploader.py

    七牛Python文档:https://developer.qiniu.com/kodo/sdk/1242/python

    相关文章

      网友评论

        本文标题:批量替换markdown本地图片地址为七牛外链

        本文链接:https://www.haomeiwen.com/subject/xklhjqtx.html