用python将md文件简单地转成tex文件(代码)

批量将博客的源.md 文件转换成 .tex 文件, 因为 VsCode 的插件转换出来的 .pdf 文件似乎没办法转换公式. 我就用 python 写了一个程序将所有的博客文件转换成 .tex, 因为我的博客主要都是数学公式. (万能的 python ).

代码本身没有任何营养, 就转换了一个 title , 去掉了头部的说明字段, 再将章节名转换为 section, subsection.

代码如下:

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
import os


def convert(path):
print(f"converting {path} ...")
with open(path, "r", encoding="utf8") as file:

art = file.readlines()
title = path.split("\\")[-1].split(".")[0]
flag = 2
art1 = [
"%! TeX program = xelatex\n\\documentclass[UTF8]{cteXart}\n\\usepackage{CJKfntef}\n\\usepackage{amsmath}\n"
"\\usepackage{amsfonts}\\usepackage{amssymb}\n\\usepackage{enumerate}\n\\usepackage{multirow}"
"\\usepackage{geometry}\n\\geometry{top=0cm, bottom=0.5cm, left=2.5cm, right=2.5cm}\n\\usepackage{tabularx}",
f"\\title{{{title}}}",
"\\begin{document}\\maketitle\\tableofcontents"
]
for line in art:
if line.startswith("---"):
flag -= 1
continue
if flag:
continue
if line.startswith("###"):
line1 = "".join(line.split()[1:])
art1.append(f"\\subsubsection{{{line1}}}")
elif line.startswith("##"):
line1 = "".join(line.split()[1:])
art1.append(f"\\subsection{{{line1}}}")
elif line.startswith("#"):
line1 = "".join(line.split()[1:])
art1.append(f"\\section{{{line1}}}")
else:
art1.append(line.strip())
art1.append("\\end{document}")

to = r"D:\VsCode\TeXProject\convert"
with open(to+"\\" + title + ".tex", "w", encoding="utf8") as file:
file.write("\n".join(art1))


if __name__ == '__main__':
dir1 = r"D:\VsCode\blogProj\MathNote\source\_posts"
for file in os.listdir(dir1):
if file.endswith(".md"):
convert(path=dir1 + "\\" + file)

文章作者: Letter Wu
文章链接: https://letterwu.github.io/2022/04/09/用python将md文件简单地转成tex文件-代码/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 Have a nice day~ | Letter Wu's BLOG
支付宝打赏
微信打赏