import re,os
import shutil
class markdownManager:
def read(self,filename):
res = ""
with open(filename, "r+", encoding="utf-8") as fs:
res = fs.read()
return res
def write(self,filename, str):
with open(filename, "w", encoding="utf-8") as fs:
fs.write(str)
def pipei(self,string, suffix=["png", "jpg", "gif"]):
res = []
for s in suffix:
res += re.findall('img/.*\.{}'.format(s), string)
return res
def qiefeng(self,str1):
res = str1.split("/")
if len(res) > 0: return res[-1]
return ""
def mycopyfile(self,srcfile, dstpath): # 复制函数
# srcfile 需要复制、移动的文件
# dstpath 目的地址
if not os.path.isfile(srcfile):
print("%s not exist!" % (srcfile))
else:
fpath, fname = os.path.split(srcfile) # 分离文件名和路径
if not os.path.exists(dstpath):
os.makedirs(dstpath) # 创建路径
shutil.copy(srcfile, dstpath + fname) # 复制文件
print("copy %s -> %s" % (srcfile, dstpath + fname))
# 遍历文件目录
find_md = lambda root_path: [l for l in os.listdir(root_path) if l.find(".md") > 0]
def manageRun(self,root_path, md_name, imges_path, save_name="img"):
'''
注意:路径需要以 / 结尾
:param root_path: markdown文件目录,如 "data/01.java基础进阶/"
:param md_name: markdown文件名,如 "01.类和对象.md"
:param imges_path: 原始图片路径(原始),如 "data/images/"
:param save_name: 图片储存文件夹名(新的),默认 "img"
:return:
'''
str2 = self.read(root_path + md_name)
print("文本长度:", len(str2))
new_path = "new{}{}/".format(root_path, save_name)
img_path = self.pipei(str2)
for i in img_path:
filename = self.qiefeng(i)
str2 = str2.replace(i, save_name + "/" + filename)
self.mycopyfile(imges_path + filename, new_path)
self.mycopyfile(root_path + md_name, "new" + root_path)
self.write("new" + root_path + md_name, str2)
# 使用方法
'''
说明:目录文件必须以 \ 结尾
"data/":markdown文件目录
"java基础进阶.md":需要整理的markdown文件名
"data/img/java基础进阶/":markdown文件的存储图片目
"img":整理mardown后图片储存的文件名
'''
markdownManager().manageRun("data/","java基础进阶.md","data/img/java基础进阶/","img")
整理后: