前言

描述

上次写了根据markdown自动取回放在图床的图片,这次则是对markdown文件进行操作,替换特定字符串

如果你需要:

  • 更改相对地址为绝对地址,例如

    1
    /1.jpg  to http://yourblog.domain/1.jpg
  • 写拖拽图片生成的路径更改为服务器上图片的路径,例如

    1
    C:\Users\Hasee\Desktop\1.jpg to http://yourblog.domain/picture/1.jpg

    这篇文章可能对你有帮助

开始

程序

Python3程序

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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
'''
Author: LX
Blog: blog.lxscloud.top
'''

import os

mddir = './md/' #设置输入路径
outmddir = './output-md/' #设置输出路径
markdown_setup = ["![", "](", ")"]#仅图片markdown格式会被处理
markdown_setup_blacklist = ["![\"", "\"](", "](\""]#用于排除混淆,防止一些错误
download_list = ["https://", "http://", "\\"]#仅http、https和\会被处理
ext_name = ["md"]#扩展名白名单,只处理扩展名为.md的文件

'''
#例子:
replace_source = ['\\']
replace_target = ['/']
'''
#要被替换的字符,请加""或''
replace_source = ['\\']
#要被替换的目标字符
#(replace_source里面的字符将会替换成replace_target里你写的字符)
#要求数据类型为字符串,请加""或''
#两个列表需对齐
replace_target = ['/']

#函数:检查目录是否存在,不存在则新建
def checkdir_andcreate(dir_path_set):
if dir_path_set[-1:] == "":
dir_path_set = dir_path_set[0:-1]
if os.path.isdir(dir_path_set) == False:
try:
os.mkdir(dir_path_set)
except:
print("Dir create fail")
exit()
print("Now create a new dir, path:", dir_path_set)

#函数:特点字符查找
def check_mark(str_line, list_check, mode_check):
resault_check = False
for i in list_check:
if mode_check == True:#模式True:列表中的所有字符都要有,一个都不能少
resault_check = True
try:
str_line.index(i)
except:
resault_check = False
break
elif mode_check == False:#模式False:只要匹配到列表中字符的其中一个就行
resault_check = False
state = 0
try:
str_line.index(i)
state = 1
except:
state = 0
if state == 1:
resault_check = True
break
else:
resault_check = False
print("Function input error")
break
return resault_check

def read_and_find(file_name):
if True:
try:
with open(outmddir + file_name[file_name.rfind("/"):], 'w', encoding = 'utf-8') as fout:#在输出目录新建同名文件
file_processing = open(file_name, 'r+', encoding = 'utf-8') #读取原文件
for line in file_processing.readlines():#分行处理
lines = str(line)

if check_mark(lines, markdown_setup, True) == True and check_mark(lines, markdown_setup_blacklist, False) == False:#检测是否为markdown语法的图片链接,并且无黑名单列表中的字符
http_l = lines.index("](") + 2
http_r = lines.index(")", http_l)
pic_http_addr = lines[http_l:http_r]

if check_mark(pic_http_addr, download_list, False):#检测网址是否有效
print("String replace:", pic_http_addr ,end='')

if len(replace_source) == len(replace_target):
for iii,data_r in enumerate(replace_target):
lines = lines.replace(replace_source[iii], data_r)#处理字符

print(" to ", lines)
else:
print("****************************")
print("Error, check (replace_source) and (replace_target)")
print("****************************")

fout.write(lines)#写入文本

file_processing.close()
return True
except:
print("Err at read file :", file_name)
return False


checkdir_andcreate(mddir)
checkdir_andcreate(outmddir)
dict_pic_path = []
list = os.listdir(mddir) #列出文件夹下所有的目录与文件
for i in range(0,len(list)):
path = os.path.join(mddir,list[i])
if os.path.isfile(path):
str_path = str(path)
str_path = str_path[str_path.rfind(".")+1:]
for i in ext_name: #忽略不在白名单的扩展名
if str_path == i:
#print(path)
dict_pic_path.append(path)
break

for i in dict_pic_path:#挨个处理文件
print("File:", i)
print("-----------------------------------")
read_and_find(i)
print("-----------------------------------\n")

使用方法

保存上述文件为 .py (*为自己定的文件名),使用python3运行

此程序可批量处理md文件

运行

初次运行会产生md和output-md文件夹

360截图17001019659085

处理后的文件将保存于output-md目录,

处理前的文件将不做任何修改,

可以保存原文件

请将待处理markdown文件放入md文件夹

  • 新建一个markdown文件作为演示
  • 在markdown编辑器拖拽图片,自动生成markdown语法的图片链接

360截图17640214507855

  • 放入output-md目录

360截图18720124202142

360截图171008136511195

  • 对参数进行一些调整–把\变成/

360截图18720123175660

  • 然后替换成绝对地址

360截图17891228278027

注意:顺序必须注意,上面这样写会先把\换成/,然后才对C:/Users/Hasee/Desktop/进行替换

由于C:\Users\Hasee\Desktop\已经被替换成C:/Users/Hasee/Desktop/,所以下面指出的地址中的\要换成/,也就是像上图那样写

360截图17640214507855

  • 然后再次运行程序

360截图16570201556157

即可在output-md目录看到输出文件

360截图1682121688142116

查看文件可见

原文件:

360截图17640214507855

操作之后:

360截图17571114102151137

状况

使用python2.7会出错

请使用python3解释器运行

1
python3

Dir create fail

程序可能没有创建目录的权限或目录不可写

Err at read file

无法读取markdown文件,可能是没有读取权限

Now create a new dir

文件夹不存在,创建文件夹成功

Function input error

对程序改动有错

Error, check (replace_source) and (replace_target)

列表replace_source和列表replace_target填写的值数目不相等,建议检查

File:

在处理的当前文件

结束

谢谢观看,本文使用此程序处理,未发现问题

EOF