Markdown是一种简单的标记语言,用易读易写的纯文本格式编写文档。Python的markdown模块可以把Markdown文本转换成html网页格式。
首先需要安装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文件:
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页面,可以这样处理:
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转换功能:
使用markdown模块可以: - 自动化文档生成流程 - 创建静态网站内容 - 转换技术文档 - 生成博客文章
本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!