11-08 周三 解决csdn外链转存失败问题

简介

 在使用typora + picGO撰写自己的博客时,图像已经转换为了静态资源,但发表在CSDN上,如果直接复制粘贴,csdn会将其中的图片链接再次转存到自己的图像服务器中,这有很大的问题。那么如何解决这个问题呢?

问题描述

 在我们写好的markdown文件中,会存在很多如下的内容:
11-08 周三 解决csdn外链转存失败问题_第1张图片
 而csdn在检测到相关内容时,会自动进行外链图片下载和存储,但非常容易失败。一个一个下载又非常耗时耗力。

11-08 周三 解决csdn外链转存失败问题_第2张图片
而使用标签,则不需要进行转存。
11-08 周三 解决csdn外链转存失败问题_第3张图片

解决方式

解决方式一: 使用vscode编辑器

核心思想: 使用正则匹配,通过提取Group来实现功能。

 使用vs code进行替换。将模式替换为
使用替换功能,开启正则表达式功能:
在查询框中输入:

!\[.*\]\((.*?)\)

然后在替换框中输入如下内容:


然后全局替换,即可完整markdown的图片转换为资源的,而且不会再次触发外链图像转存了。

解决方式二: 代码片段


# -*- coding: utf-8 -*-
# @Author: yq1ng
# @Date:   2021-05-20 17:22:08
# @Last Modified by:   yq1ng
# @Last Modified time: 2021-05-20 18:19:47

import re
import argparse
import os

def parse_argument():
    parser = argparse.ArgumentParser(description="main")
    parser.add_argument('--old_file', type=str, default=-1, help='original md file')

    return parser.parse_args()

if __name__ == '__main__':
    args = parse_argument()
    old_path = args.old_file
    if not os.path.isfile(old_path):
        raise ValueError("请输入有效的文件")
    
    print(f"old_file: {old_path}")
    md_path = os.path.dirname(old_path)
    file_name = os.path.basename(old_path)
    new_path = os.path.join(md_path, "csdn-"+file_name)
    old_file = open(old_path, 'r', encoding='utf-8')
    new_file = open(new_path, 'w', encoding='utf-8')

    old_line = old_file.readline()
    count = 0

    while old_line:
        if "![" in old_line:
            url = re.findall('https://.*png|https://.*jpeg|https://.*jpg|https://.*JPG', old_line)
            img = '+ url[0] + '"/>'
            new_line = re.sub('!\[.*\)', img, old_line)
            new_file.write(new_line)
            print(old_line + '   ===>   ' + new_line)
            count += 1
        else:
            new_file.write(old_line)
        old_line = old_file.readline()

    old_file.close()
    new_file.close()

    print('\n已成功替换' + str(count) + '处外链问题')
    ```
    

你可能感兴趣的:(vscode)