The value of knowledge lies not in possession, but in share.

0%

Python--批量更改Markdown文件中的七牛云图床链接

背景介绍

这两天阿里云将我的域名(wangcong.info)的备案取消接入并向工信部提交了注销申请。于是乎,我先后收到了几个短信和邮件通知,贴出一条如下:

今早,本站点中图片便已经无法正常显示,我赶紧用早已备案的另外一域名(babibobi.com)在七牛云上予以了替换,暂时解决图片不能访问的问题。

因为Markdown文件中有很多图片链接,一一更换的话,工作量略大,通过查资料,写了一个Python脚本,进而可以实现一键批量更改Markdown文件中的七牛云图床链接的功能。具体如下:

更改后的md文档:

实现代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# usr/bin/env python
# -*- coding:utf-8 -*-

import re, os, time, argparse
import sys, io
from itertools import chain

# Markdown中图片语法 ![](url) 或者 <img src='' />
global img_patten
img_patten = r'!\[.*?\]\((.*?)\)|<img.*?src=[\'\"](.*?)[\'\"].*?>'

def replace_md_url(md_file):
"""
批量更改Markdown文件中的七牛云图床链接
:param md_file: Markdown文件
:return:
"""
if os.path.splitext(md_file)[1] != '.md':
print('{} 不是Markdown文件,不做处理。'.format(md_file))
return

num_replace = 0
# 本次操作时间戳
dir_ts = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())

with io.open(md_file, 'r', encoding='utf-8') as f: #使用utf-8 编码打开
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 and len(match)>0 :
print("match pic : ", match)
new_url = match.replace('wangcong.info','babibobi.com')

# 更新MarkDown文件中的URL
if new_url :
post = post.replace(match, new_url)
num_replace = num_replace + 1

# 如果有内容的话,就直接覆盖写入当前的MarkDown文件
if post and num_replace > 0:
io.open(md_file, 'w', encoding='utf-8').write(post)
print('{0} 中有{1}个URL被替换/{2}'.format(os.path.basename(md_file), num_replace, dir_ts))
elif num_replace == 0:
print('{} 中没有需要替换的URL'.format(os.path.basename(md_file)))


if __name__ == '__main__':

fileset = os.listdir(sys.argv[1])
for filename in fileset:
print filename
absfile = os.path.join(sys.argv[1], filename)
replace_md_url(absfile)

🍭支持一根棒棒糖吧!