侧边栏壁纸
  • 累计撰写 2,058 篇文章
  • 累计创建 73 个标签
  • 累计收到 20 条评论

目 录CONTENT

文章目录

使用Python将Markdown文件转为html

大猿本猿
2021-11-14 / 908 阅读 / 0 字

1.需要用到的库

markdown==3.3.4
python-markdown-math==0.8
markdown-checklist==0.4.3
pymdown-extensions==9.0

2.全部代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Describe:markdown文件转为html文件

import markdown
import os

from pymdownx import superfences


class MarkdownToHtml:
    def __init__(self,md_filename,encoding='utf-8'):
        self.md_filename = md_filename
        self.encoding = encoding
        self._args()

    """
    设置参数
    :return: 
    """
    def _args(self):
        self.html = ""
        # 扩展配置
        self.extensions = [
            'toc',  # 目录,[toc]
            'extra',  # 缩写词、属性列表、释义列表、围栏式代码块、脚注、在HTML的Markdown、表格
        ]
        third_party_extensions = [
            'mdx_math',  # KaTeX数学公式,$E=mc^2$和$$E=mc^2$$
            'markdown_checklist.extension',  # checklist,- [ ]和- [x]
            'pymdownx.magiclink',  # 自动转超链接,
            'pymdownx.caret',  # 上标下标,
            'pymdownx.superfences',  # 多种块功能允许嵌套,各种图表
            'pymdownx.betterem',  # 改善强调的处理(粗体和斜体)
            'pymdownx.mark',  # 亮色突出文本
            'pymdownx.highlight',  # 高亮显示代码
            'pymdownx.tasklist',  # 任务列表
            'pymdownx.tilde',  # 删除线
        ]
        self.extensions.extend(third_party_extensions)
        self.extension_configs = {
            '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 markdown_to_html(self, html_name):
        try:
            with open(self.md_filename, "r", encoding=self.encoding) as file_md:
                md_text = file_md.read()
        except Exception as e:
            print("<Error>", e)
            return False

        title = '.'.join(os.path.basename(self.md_filename).split('.')[:-1])
        html_text = markdown.markdown(md_text, output_format='html', extensions=self.extensions,extension_configs=self.extension_configs)  # MarkDown转HTML
        # self.html = self.html.format(title, html_text)
        self.html = html_text

        try:
            with open(html_name, 'w', encoding=self.encoding) as file_html:
                file_html.write(self.html)
        except Exception as e:
            print("<Error>", e)
            return False

        return True


if __name__ == '__main__':
    file_path = r'C:\Users\Administrator\Desktop\11\\'
    md_name = file_path+"如何使用log4j的logger打印Drools的调试日志信息.md"
    html_name = file_path+"如何使用log4j的logger打印Drools的调试日志信息2.html"

    if(MarkdownToHtml(md_name).markdown_to_html(html_name)):
        print('转换完成')