Python3入门指南Python语言的特点和实际应用Python3环境搭建配置VSCode进行Python开发Python基础语法Python变量与数据类型Python数据类型转换Python解释器使用Python注释使用Python运算符Python数字类型Python字符串操作Python列表操作Python元组使用Python字典使用Python集合使用Python条件控制详解Python循环语句详解Python编程入门实践Python推导式详解Python迭代器和生成器Python with语句详解Python函数详解Python lambda(匿名函数)Python装饰器Python数据结构Python模块和包使用Python中__name__和__main__的用法Python输入输出:从基础到文件操作Python文件操作Python OS模块使用Python错误和异常处理Python面向对象编程Python命名空间和作用域Python虚拟环境:venv详细教程Python类型注解Python标准库常用模块Python正则表达式Python CGI编程Python MySQL(mysql-connector驱动)Python MySQL(PyMySQL驱动)Python网络编程Python发送邮件Python多线程编程Python XML解析Python JSON解析Python日期和时间处理Python操作MongoDBPython urllib库使用Python uWSGI 安装与配置Python pip包管理工具Python operator模块Python math模块Python requests模块HTTP请求Python random模块Python OpenAI库Python AI绘画制作Python statistics模块Python hashlib模块:哈希加密Python量化交易Python pyecharts数据可视化Python Selenium网页自动化Python BeautifulSoup网页数据提取Python Scrapy爬虫框架Python Markdown转HTMLPython sys模块Python Pickle模块:数据存储Python subprocess模块Python queue队列模块Python StringIO内存文件操作Python logging日志记录Python datetime日期时间处理Python re正则表达式Python csv表格数据处理Python threading 多线程编程Python asyncio 异步编程Python PyQt 图形界面开发Python 应用方向和常用库框架

Python Markdown转HTML

Markdown是一种简单的标记语言,用易读易写的纯文本格式编写文档。Python的markdown模块可以把Markdown文本转换成html网页格式。


安装markdown模块

首先需要安装markdown模块:

pip install markdown

安装完成后就可以在Python中使用markdown转换功能了。


基本转换方法

转换简单文本

import markdown

# 准备Markdown文本
md_content = """
# 这是一个主标题

这是一个段落,包含**粗体**和*斜体*文字。

## 这是一个二级标题

- 列表项1
- 列表项2
- 列表项3

[访问fly63网站](https://www.fly63.com)
"""

# 转换为HTML
html_output = markdown.markdown(md_content)

# 显示转换结果
print(html_output)

运行上面的代码,会输出对应的HTML代码:

<h1>这是一个主标题</h1>
<p>这是一个段落,包含<strong>粗体</strong>和<em>斜体</em>文字。</p>
<h2>这是一个二级标题</h2>
<ul>
<li>列表项1</li>
<li>列表项2</li>
<li>列表项3</li>
</ul>
<p><a href="https://www.fly63.com">访问fly63网站</a></p>

转换Markdown文件

更常见的情况是转换整个Markdown文件:

import markdown

def convert_markdown_file(md_file, html_file):
    """将Markdown文件转换为HTML文件"""
    try:
        # 读取Markdown文件
        with open(md_file, 'r', encoding='utf-8') as file:
            markdown_text = file.read()
        
        # 转换为HTML
        html_content = markdown.markdown(markdown_text)
        
        # 写入HTML文件
        with open(html_file, 'w', encoding='utf-8') as file:
            file.write(html_content)
        
        print(f"转换成功: {md_file} -> {html_file}")
        
    except FileNotFoundError:
        print(f"文件不存在: {md_file}")
    except Exception as e:
        print(f"转换出错: {e}")

# 使用示例
convert_markdown_file('document.md', 'document.html')


完整的HTML页面生成

上面的转换只生成HTML片段,如果需要完整的HTML页面,可以这样处理:

import markdown

def create_full_html_page(md_file, html_file, title="文档"):
    """生成完整的HTML页面"""
    try:
        # 读取Markdown内容
        with open(md_file, 'r', encoding='utf-8') as file:
            markdown_content = file.read()
        
        # 转换为HTML
        html_body = markdown.markdown(markdown_content)
        
        # 构建完整的HTML页面
        full_html = f"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{title}</title>
    <style>
        body {{
            font-family: Arial, sans-serif;
            line-height: 1.6;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            color: #333;
        }}
        h1, h2, h3 {{
            color: #2c3e50;
        }}
        code {{
            background-color: #f4f4f4;
            padding: 2px 4px;
            border-radius: 3px;
        }}
        pre {{
            background-color: #f4f4f4;
            padding: 15px;
            border-radius: 5px;
            overflow-x: auto;
        }}
        a {{
            color: #3498db;
            text-decoration: none;
        }}
        a:hover {{
            text-decoration: underline;
        }}
    </style>
</head>
<body>
{html_body}
</body>
</html>"""
        
        # 保存HTML文件
        with open(html_file, 'w', encoding='utf-8') as file:
            file.write(full_html)
        
        print(f"完整HTML页面已生成: {html_file}")
        
    except Exception as e:
        print(f"生成页面出错: {e}")

# 使用示例
create_full_html_page('README.md', 'index.html', '项目说明文档')


实际应用示例

博客文章转换

import markdown
from datetime import datetime

def convert_blog_post(md_file, output_dir="output"):
    """转换博客文章"""
    import os
    
    # 创建输出目录
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    try:
        # 读取文章
        with open(md_file, 'r', encoding='utf-8') as file:
            content = file.read()
        
        # 提取标题(假设第一行是标题)
        lines = content.split('\n')
        title = lines[0].replace('#', '').strip() if lines[0].startswith('#') else "无标题"
        
        # 转换内容
        html_content = markdown.markdown(
            content, 
            extensions=['fenced_code', 'tables', 'toc']
        )
        
        # 生成文件名
        base_name = os.path.splitext(os.path.basename(md_file))[0]
        html_file = os.path.join(output_dir, f"{base_name}.html")
        
        # 创建完整的博客页面
        blog_template = f"""<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>{title}</title>
    <style>
        body {{
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.7;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            color: #333;
            background-color: #f9f9f9;
        }}
        .article {{
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }}
        h1 {{
            color: #2c3e50;
            border-bottom: 2px solid #3498db;
            padding-bottom: 10px;
        }}
        code {{
            background: #f4f4f4;
            padding: 2px 6px;
            border-radius: 3px;
        }}
        pre {{
            background: #2d2d2d;
            color: #f8f8f2;
            padding: 15px;
            border-radius: 5px;
            overflow-x: auto;
        }}
        .meta {{
            color: #7f8c8d;
            font-size: 0.9em;
            margin-bottom: 20px;
        }}
    </style>
</head>
<body>
    <div>
        <h1>{title}</h1>
        <div>
            生成时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
        </div>
        {html_content}
    </div>
</body>
</html>"""
        
        # 保存文件
        with open(html_file, 'w', encoding='utf-8') as file:
            file.write(blog_template)
        
        print(f"博客文章已生成: {html_file}")
        return html_file
        
    except Exception as e:
        print(f"转换博客文章失败: {e}")
        return None

# 使用示例
convert_blog_post("my_blog_post.md")

批量转换工具

import markdown
import os
import glob

def batch_convert_markdown(input_dir, output_dir, extensions=None):
    """批量转换Markdown文件"""
    
    if extensions is None:
        extensions = ['fenced_code', 'tables']
    
    # 创建输出目录
    if not os.path.exists(output_dir):
        os.makedirs(output_dir)
    
    # 查找所有Markdown文件
    md_files = glob.glob(os.path.join(input_dir, "*.md"))
    
    if not md_files:
        print(f"在 {input_dir} 中没有找到Markdown文件")
        return
    
    success_count = 0
    
    for md_file in md_files:
        try:
            # 读取文件
            with open(md_file, 'r', encoding='utf-8') as file:
                md_content = file.read()
            
            # 转换
            html_content = markdown.markdown(md_content, extensions=extensions)
            
            # 生成输出文件名
            base_name = os.path.splitext(os.path.basename(md_file))[0]
            html_file = os.path.join(output_dir, f"{base_name}.html")
            
            # 保存
            with open(html_file, 'w', encoding='utf-8') as file:
                file.write(html_content)
            
            success_count += 1
            print(f"✓ 转换成功: {os.path.basename(md_file)}")
            
        except Exception as e:
            print(f"✗ 转换失败 {os.path.basename(md_file)}: {e}")
    
    print(f"\n批量转换完成: {success_count}/{len(md_files)} 个文件成功")

# 使用示例
batch_convert_markdown("markdown_files", "html_output")


高级功能

自定义扩展

import markdown
from markdown.extensions import Extension
from markdown.preprocessors import Preprocessor

class CustomExtension(Extension):
    def extendMarkdown(self, md):
        # 添加自定义处理逻辑
        md.preprocessors.register(CustomPreprocessor(md), 'custom', 175)

class CustomPreprocessor(Preprocessor):
    def run(self, lines):
        new_lines = []
        for line in lines:
            # 自定义处理:将 ==文本== 转换为 <mark>文本</mark>
            if '==' in line:
                line = line.replace('==', '<mark>', 1)
                line = line.replace('==', '</mark>', 1)
            new_lines.append(line)
        return new_lines

# 使用自定义扩展
md_text = "这是 ==重要== 的文本。"
html = markdown.markdown(md_text, extensions=[CustomExtension()])
print(html)  # 输出: <p>这是 <mark>重要</mark> 的文本。</p>

代码高亮

import markdown

def convert_with_syntax_highlighting(md_file, html_file):
    """带代码高亮的转换"""
    
    # 读取Markdown内容
    with open(md_file, 'r', encoding='utf-8') as file:
        md_content = file.read()
    
    # 使用代码高亮扩展
    extensions = [
        'fenced_code',
        'codehilite'
    ]
    
    extension_configs = {
        'codehilite': {
            'css_class': 'highlight',
            'linenums': True
        }
    }
    
    html_content = markdown.markdown(
        md_content, 
        extensions=extensions,
        extension_configs=extension_configs
    )
    
    # 添加代码高亮CSS
    highlight_css = """
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/github.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>
    <script>hljs.highlightAll();</script>
    """
    
    full_html = f"""
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <title>代码高亮示例</title>
        {highlight_css}
    </head>
    <body>
        {html_content}
    </body>
    </html>
    """
    
    with open(html_file, 'w', encoding='utf-8') as file:
        file.write(full_html)
    
    print(f"带代码高亮的HTML已生成: {html_file}")


总结

Python的markdown模块提供了强大的Markdown到HTML转换功能:

  • 基本转换:简单的文本转换
  • 文件处理:读取.md文件,输出.html文件
  • 扩展支持:表格、代码高亮、目录等高级功能
  • 自定义样式:生成带CSS样式的完整HTML页面
  • 批量处理:一次性转换多个文件

使用markdown模块可以: - 自动化文档生成流程 - 创建静态网站内容 - 转换技术文档 - 生成博客文章

本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!

链接: https://fly63.com/course/36_2136

目录选择