当前位置:网站首页>长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)
边栏推荐
猜你喜欢
神经网络如何提高准确率,神经网络的求解方式
How to realize full backup and incremental backup of MySQL database
干货:服务器网卡组技术原理与实践
电力系统潮流计算(牛顿-拉夫逊法、高斯-赛德尔法、快速解耦法)【6节点 9节点 14节点 26节点 30节点 57节点】(Matlab代码实现)
李斌带不动的长安新能源高端梦,华为和“宁王”能救吗?
cube-studio配置镜像仓库并允许
2022 CCF China Open Source Conference Notice (Fourth Round)
Pytorch GPU模型推理时间探讨
C语言按位运算符如何使用
险资又做LP,一出手40亿
随机推荐
leetcode:159.最多有两个不同字符的最长子串
mysql包select结果无法同步的问题
【科研】常见火灾数据集
C专家编程 第10章 再论指针 10.5 使用指针向函数传递一个多维数组
C language symbols on how to use
promise笔记(四)
FTXUI基础笔记(hello world)
还在用 Xshell?你 out 了,推荐一个更现代的终端连接工具,好用到爆!
1001 A+B Format(字符串处理)
如何搭建知识库,让您的内容更丰富?
Embedded Development: Embedded Basics - Mapping Peripherals Using Arrays of Pointers
开源生态与AI芯片的碰撞&Dragonfly基于P2P的镜像加速系统 | 第 39-40 期
C专家编程 第10章 再论指针 10.8 轻松一下---程序检验的限制
神经网络的图像识别技术,神经网络识别图像原理
百日刷题挑战--错题01day
C专家编程 第10章 再论指针 10.4 向函数传递一个一维数组
一文带你彻底拿下a,b两点间等效电阻
使用Jedis连接linux上的redis
注解和反射、持续
一颗完整意义的LPWAN SOC无线通信芯片——ASR6601