⽤python实现markdown转html
1. 前⾔
现在markdown已经是⾮常常⽤的记录⼯具了,整齐的排版、代码⾼亮、图⽚表格样样齐全,同时也⽀持html标签,是⾮常好⽤的⼀种⼯具(语法)。
那么今天来分享⼀下使⽤python实现markdown⽂件转为html,⽽且也能很好显⽰代码和整齐的排版。
2. 正⽂
2.1 使⽤到的库
markdown
python-markdown-math
markdown_checklist
pymdown-extensions
2.2 ⽂章思路
本⽂的主要功能是讲markdown转为html,在上述博客中还带有转换为pdf的功能,但个⼈觉得转为pdf没什么必要,在此就没添加上了。除此之外,在原有的基础上添加了⽂章⽬录的⼩模块,算是⼀点⼩⼩的改进吧。
2.3 功能代码
这⾥就直接上代码了>>>
import os
try:
from markdown import markdown
except ModuleNotFoundError as e:
os.system("pip install markdown")
os.system("pip install python-markdown-math")
os.system("pip install markdown_checklist")
from markdown import markdown
try:
from pymdownx import superfences
except ModuleNotFoundError as e:
os.system("pip install pymdown-extensions")
from pymdownx import superfences
class mdtox:
def __init__(self, md_filename, encoding='utf-8'):
self.md_filename = md_filename
self.__args()
def __args(self):
self.html = '''
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimal-ui">
<title>{}</title>
<link rel="stylesheet" href="filesblogs/files/bpf-1024/linenum.css">
<link rel="stylesheet" href="filesblogs/files/bpf-1024/markdown.css">
<link rel="stylesheet" href="filesblogs/files/bpf-1024/tasklist.css">
<link rel="stylesheet" href="filesblogs/files/bpf-1024/codehighlight.css">
<link rel="stylesheet" href="filesblogs/files/bpf-1024/directory.css">
pdf转html<link rel="stylesheet" href="cdn.jsdelivr/npm/katex/dist/katex.min.css" crossorigin="anonymous">
<script src="filesblogs/files/bpf-1024/directory.js"></script>
<script src="unpkg/mermaid@8.7.0/dist/mermaid.min.js"></script>
<script src="cdn.jsdelivr/npm/katex/dist/katex.min.js" crossorigin="anonymous"></script>
<script src="cdn.jsdelivr/npm/katex/dist/contrib/mathtex-script-type.min.js" defer></script>
</head>
<body>
<article class="markdown-body" id="markdown-body">
{}
</article>
</body>
</html>
'''
# 扩展配置
'toc', # ⽬录,[toc]
'extra', # 缩写词、属性列表、释义列表、围栏式代码块、脚注、在HTML的Markdown、表格
]
third_party_extensions = [
'mdx_math', # KaTeX数学公式,$E=mc^2$和$$E=mc^2$$
'sion', # checklist,- [ ]和- [x]
'pymdownx.magiclink', # ⾃动转超链接,
'pymdownx.caret', # 上标下标,
'pymdownx.superfences', # 多种块功能允许嵌套,各种图表
'pymdownx.betterem', # 改善强调的处理(粗体和斜体)
'pymdownx.mark', # 亮⾊突出⽂本
'pymdownx.highlight', # ⾼亮显⽰代码
'pymdownx.tasklist', # 任务列表
'pymdownx.tilde', # 删除线
]
'mdx_math': {
'enable_dollar_delimiter': True # 允许单个$
},
'pymdownx.superfences': {
"custom_fences": [
{
'name': 'mermaid', # 开启流程图等图
'class': 'mermaid',
'format': superfences.fence_div_format
}
]
},
'pymdownx.highlight': {
'linenums': True, # 显⽰⾏号
'linenums_style': 'pymdownx-inline' # 代码和⾏号分开
},
'pymdownx.tasklist': {
'clickable_checkbox': True, # 任务列表可点击
}
}
def to_html(self, html_name):
try:
with open(self.md_filename, "r", ding) as file_md:
md_text = ad()
except Exception as e:
print("<Error>", e)
return False
title = '.'.join(os.path.basename(self.md_filename).split('.')[:-1])
html_text = markdown(md_text, output_format='html', sions, extension_sion_configs) # MarkDown转HTML
self.html = self.html.format(title, html_text)
try:
with open(html_name, 'w', ding) as file_html:
file_html.write(self.html)
except Exception as e:
print("<Error>", e)
return False
return True
2.4 使⽤⽅法
这⾥我封装了下载依赖库,所以只要运⾏python代码即可。其中的js⽂件、css⽂件都在我的博客⽂件中,所以只要有⽹都可以轻松访问⽣成的html⽂件,若想离线使⽤,就把需要的⽂件下载到本地,然后引⼊即可。
或者你可以选择创建⼀个虚拟环境:
# 本测试与上述代码在同个⽂件中
if __name__ == '__main__':
md_name = "E:/java.md"
html_name = "E:/java.html"
if(mdtox(md_name).to_html(html_name)):
print('转换完成')
发布评论