当前位置:网站首页>长markdown文档的拆分与合并
长markdown文档的拆分与合并
2022-08-10 16:52:00 【zdlwhereyougo】
目的
使用vscode写长markdown文档时,实时渲染会卡顿,不方便检查,拆分成每一部分比较好检查。
在导出全文的时候,需要保证交叉引用不会出问题,最好再合并成一个文档。万能python实现了这个功能。这个功能不难,参考了站内【羊城迷鹿】的文章,对他的函数进行了改动,更符合我的要求。
from os.path import basename
import re
import os
from urllib.parse import quote
import warnings
warnings.filterwarnings('ignore')
def get_subtitle(content):
# 从md文件中获取h1标题
# 返回日期和索引
pattern = re.compile(r'#{1}(.*?)\n')#正则表达
heads = pattern.findall(content)
# print(heads)
# 防止出现空h1标题
subtitle = [h[1:] for h in heads if h[0] == ' ' and len(h) > 2]#以井号开头
indexes = [content.find(title+'\n')-2 for title in subtitle]
indexes.append(len(content))
return subtitle, indexes
def save_md(path, article):
# 保存分割后的文件
with open(path, 'w+', encoding='utf8') as f:
f.write(article)
def split_and_save_md(filepath,savepath):
file_path,fullflname = os.path.split(filepath)
fname,ext = os.path.splitext(fullflname)
with open(filepath, 'r+', encoding='utf8') as f:
content = f.read()
if not os.path.exists(savepath):
os.mkdir(savepath)
sub_title, indexes = get_subtitle(content)
for i in range(len(sub_title)):
article_path = savepath+'/'+fname+'_'+sub_title[i]+'.md'
if os.path.exists(article_path):
continue
article = content[indexes[i]:indexes[i+1]]
save_md(article_path, article)
# 再定义一个合并文件的
# 合并的代码
def combine_md(filepath,savepath):
md_list = os.listdir(savepath)#列出保存路径下所有的md文件
file_path,fullflname = os.path.split(filepath)
fname,ext = os.path.splitext(fullflname)
fname_split=fname+'_'
contents = []
for md in md_list:
if fname_split in md:
md_file =savepath + '\\' + md
with open(md_file, 'r', encoding='utf-8') as file:
contents.append(file.read() + "\n")
#构造输出路径
output_path=savepath+'\\'+fname+'.md'
with open(output_path,"w", encoding='utf-8') as file:
file.writelines(contents)
#拆分成小部分,更好查看,原始文件所在目录
filepath=r'D:\BaiduNetdiskWorkspace\V6.md'
#拆分后文件所在目录,为了方便,需要新建一个文件夹
savepath=r'D:\BaiduNetdiskWorkspace\newV6t'
#执行拆分命令
split_and_save_md(filepath,savepath)
#执行合并命令
# combine_md(filepath,savepath)
边栏推荐
猜你喜欢
随机推荐
阿里工作7年,肝到P8就剩这份学习笔记了,已助朋友拿到10个Offer
轮询以及webSocket与socket.io原理
C language symbols on how to use
Lua--table操作
雷达存在感应器技术,实时感知控制应用,雷达人体探测方案
ahx文件转mav文件 工具分享及说明
观测云入选 CNCF 云原生全景图
生成树协议(STP---Spanning Tree Protocol)
电力系统潮流计算与PowerWorld仿真(牛顿拉夫逊法和高斯赛德尔法)(Matlab实现)
建筑施工员证怎么考?报名条件及报考时间是什么?
找到一个超级神奇,百试百灵的解决 ModuleNotFoundError: No module named xxx 的方法
【云原生| Docker】 部署 Django & mysql 项目
教你自己搭建一个IP池(绝对超好用!!!!)
mysql包select结果无法同步的问题
v-show指令:切换元素的显示与隐藏
神经网络有哪些激活函数,卷积神经网络有哪些
document.title获取当前网页的标题
LeetCode-1. Two Sum
一文带你彻底拿下a,b两点间等效电阻
C:枚举的优缺