| name | Markdown生成器 |
| description | 当生成Markdown文档、转换格式、创建技术文档、编写README文件或自动化文档生成时,提供完整的Markdown处理和生成解决方案。 |
| license | MIT |
Markdown生成器技能
概述
Markdown是一种轻量级标记语言,广泛用于技术文档、README文件、博客文章和项目文档。Markdown生成器能够自动化创建结构化的Markdown文档,支持格式转换、模板生成和批量处理。
核心原则: 简洁明了、结构清晰、易于维护、自动化生成。
何时使用
始终:
- 创建项目README文件
- 生成技术文档
- 编写API文档
- 创建博客文章
- 生成报告和总结
- 转换文档格式
- 批量处理Markdown文件
- 创建模板和规范
触发短语:
- "生成Markdown文档"
- "创建README模板"
- "Markdown格式转换"
- "技术文档生成"
- "API文档编写"
- "博客文章模板"
- "文档自动化"
- "Markdown处理工具"
Markdown语法和扩展
基础语法
- 标题: 使用#号表示1-6级标题
- 段落: 空行分隔段落
- 强调: 斜体、粗体、粗斜体
- 列表: 无序列表(-)、有序列表(1.)
- 链接: 文本
- 图片:

- 代码:
行内代码、代码块
扩展语法
- 表格: |列1|列2|
- 代码块语法高亮: ```language
- 任务列表: - [x] 已完成
- 脚注: ^1
- 定义列表: : 定义
- 数学公式: $LaTeX$
- 图表: Mermaid、PlantUML
常见文档类型
README文档
结构:
- 项目标题和简介
- 安装说明
- 使用方法
- API文档
- 贡献指南
- 许可证信息
特点:
- 简洁明了
- 突出重点
- 易于理解
- 快速上手
API文档
结构:
- API概述
- 认证方式
- 端点列表
- 请求/响应格式
- 错误处理
- 示例代码
特点:
- 结构清晰
- 示例丰富
- 错误说明
- 测试用例
技术博客
结构:
- 吸引人的标题
- 问题背景
- 解决方案
- 实现细节
- 总结展望
特点:
- 内容深入
- 代码示例
- 图文并茂
- 互动性强
代码实现示例
Markdown生成器核心类
import os
import re
from datetime import datetime
from typing import List, Dict, Optional, Union, Any
from dataclasses import dataclass
from enum import Enum
from pathlib import Path
import json
import yaml
class MarkdownElementType(Enum):
HEADING = "heading"
PARAGRAPH = "paragraph"
LIST = "list"
CODE_BLOCK = "code_block"
INLINE_CODE = "inline_code"
LINK = "link"
IMAGE = "image"
TABLE = "table"
BLOCKQUOTE = "blockquote"
HORIZONTAL_RULE = "horizontal_rule"
TASK_LIST = "task_list"
@dataclass
class MarkdownElement:
"""Markdown元素"""
type: MarkdownElementType
content: str
level: Optional[int] = None
attributes: Optional[Dict[str, Any]] = None
class MarkdownGenerator:
"""Markdown生成器"""
():
.elements: [MarkdownElement] = []
.metadata: [, ] = {}
.toc_enabled =
.toc_max_level =
() -> :
level < level > :
ValueError()
element = MarkdownElement(
=MarkdownElementType.HEADING,
content=text,
level=level
)
.elements.append(element)
() -> :
element = MarkdownElement(
=MarkdownElementType.PARAGRAPH,
content=text
)
.elements.append(element)
() -> :
prefix = ordered
content = .join( item items)
element = MarkdownElement(
=MarkdownElementType.LIST,
content=content,
attributes={: ordered}
)
.elements.append(element)
() -> :
content =
caption:
content +=
element = MarkdownElement(
=MarkdownElementType.CODE_BLOCK,
content=content,
attributes={: language, : caption}
)
.elements.append(element)
() -> :
element = MarkdownElement(
=MarkdownElementType.INLINE_CODE,
content=
)
.elements.append(element)
() -> :
title:
content =
:
content =
element = MarkdownElement(
=MarkdownElementType.LINK,
content=content,
attributes={: url, : title}
)
.elements.append(element)
() -> :
title:
content =
:
content =
element = MarkdownElement(
=MarkdownElementType.IMAGE,
content=content,
attributes={: url, : title}
)
.elements.append(element)
() -> :
content = + .join(headers) +
content += + .join([] * (headers)) +
row rows:
content += + .join(row) +
element = MarkdownElement(
=MarkdownElementType.TABLE,
content=content.strip(),
attributes={: headers, : rows}
)
.elements.append(element)
() -> :
lines = text.split()
quoted_lines = [ line lines]
content = .join(quoted_lines)
element = MarkdownElement(
=MarkdownElementType.BLOCKQUOTE,
content=content
)
.elements.append(element)
() -> :
element = MarkdownElement(
=MarkdownElementType.HORIZONTAL_RULE,
content =
)
.elements.append(element)
() -> :
items = []
task tasks:
text = task[]
checked = task.get(, )
checkbox = checked
items.append()
content = .join(items)
element = MarkdownElement(
=MarkdownElementType.TASK_LIST,
content=content,
attributes={: tasks}
)
.elements.append(element)
() -> :
.metadata[key] = value
() -> :
.toc_enabled:
headings = [
element element .elements
element. == MarkdownElementType.HEADING
element.level <= .toc_max_level
]
headings:
toc_lines = []
heading headings:
indent = * (heading.level - )
anchor = ._generate_anchor(heading.content)
toc_lines.append()
.join(toc_lines) +
() -> :
anchor = re.sub(, , text.lower())
anchor = re.sub(, , anchor)
anchor.strip()
() -> :
lines = []
.metadata:
lines.append()
lines.append()
key, value .metadata.items():
(value, (, )):
lines.append()
:
lines.append()
lines.append()
lines.append()
.toc_enabled:
toc = .generate_toc()
toc:
lines.append(toc)
lines.append()
element .elements:
lines.append(element.content)
lines.append()
.join(lines).strip()
():
content = .render()
(file_path, , encoding=) f:
f.write(content)
() -> :
.elements.clear()
.metadata.clear()
:
() -> MarkdownGenerator:
md = MarkdownGenerator()
md.add_metadata(, project_info.get(, ))
md.add_metadata(, project_info.get(, ))
md.add_metadata(, project_info.get(, ))
md.add_heading(project_info.get(, ), )
description = project_info.get(, )
badges = project_info.get(, [])
badges:
badge_line = .join(badges)
md.add_paragraph(badge_line)
md.add_paragraph(description)
md.add_heading(, )
toc_items = [
,
,
,
,
]
md.add_list(toc_items)
md.add_heading(, )
install_methods = project_info.get(, {})
install_methods:
method, instructions install_methods.items():
md.add_heading(method, )
md.add_code_block(instructions, )
:
md.add_code_block(, )
md.add_heading(, )
usage_examples = project_info.get(, [])
usage_examples:
i, example (usage_examples, ):
md.add_heading(, )
md.add_code_block(example.get(, ), example.get(, ))
example.get():
md.add_paragraph(example[])
:
md.add_code_block(, )
md.add_heading(, )
api_info = project_info.get(, {})
api_info:
endpoint, details api_info.items():
md.add_heading(endpoint, )
md.add_paragraph(details.get(, ))
details.get():
md.add_heading(, )
param_headers = [, , , ]
param_rows = []
param details[]:
param_rows.append([
param[],
param[],
param.get(, ) ,
param[]
])
md.add_table(param_headers, param_rows)
details.get():
md.add_heading(, )
md.add_code_block(details[], details.get(, ))
md.add_heading(, )
contribution_info = project_info.get(, {})
contribution_info:
md.add_paragraph(contribution_info.get(, ))
contribution_info.get():
md.add_heading(, )
md.add_list(contribution_info[])
:
md.add_paragraph()
md.add_list([
,
,
,
,
])
md.add_heading(, )
license_info = project_info.get(, )
md.add_paragraph()
md
() -> MarkdownGenerator:
md = MarkdownGenerator()
md.add_metadata(, )
md.add_metadata(, datetime.now().isoformat())
md.add_heading(, )
md.add_heading(, )
md.add_paragraph(api_info.get(, ))
base_info = api_info.get(, {})
base_info:
md.add_heading(, )
info_items = []
base_info.get():
info_items.append()
base_info.get():
info_items.append()
base_info.get():
info_items.append()
md.add_paragraph(.join(info_items))
auth_info = api_info.get(, {})
auth_info:
md.add_heading(, )
md.add_paragraph(auth_info.get(, ))
auth_info.get():
md.add_heading(, )
md.add_code_block(auth_info.get(, ), )
endpoints = api_info.get(, [])
endpoints:
md.add_heading(, )
headers = [, , ]
rows = []
endpoint endpoints:
rows.append([
endpoint.get(, ),
endpoint.get(, ),
endpoint.get(, )
])
md.add_table(headers, rows)
endpoint endpoints:
md.add_heading(, )
endpoint.get():
md.add_paragraph(endpoint[])
endpoint.get():
md.add_heading(, )
param_headers = [, , , , ]
param_rows = []
param endpoint[]:
param_rows.append([
param[],
param.get(, ),
param[],
param.get(, ) ,
param[]
])
md.add_table(param_headers, param_rows)
endpoint.get():
md.add_heading(, )
md.add_code_block(
endpoint[],
endpoint.get(, )
)
endpoint.get():
md.add_heading(, )
response = endpoint[]
response.get():
md.add_paragraph(response[])
response.get():
md.add_code_block(
response[],
response.get(, )
)
endpoint.get():
md.add_heading(, )
error_headers = [, , ]
error_rows = []
error endpoint[]:
error_rows.append([
(error[]),
error[],
error[]
])
md.add_table(error_headers, error_rows)
md
() -> MarkdownGenerator:
md = MarkdownGenerator()
md.add_metadata(, post_info.get(, ))
md.add_metadata(, post_info.get(, datetime.now().strftime()))
md.add_metadata(, post_info.get(, ))
md.add_metadata(, post_info.get(, []))
md.add_metadata(, post_info.get(, ))
md.add_heading(post_info.get(, ), )
meta_info = []
post_info.get():
meta_info.append()
post_info.get():
meta_info.append()
post_info.get():
meta_info.append()
post_info.get():
tags = .join(post_info[])
meta_info.append()
meta_info:
md.add_paragraph(.join(meta_info))
post_info.get():
md.add_heading(, )
md.add_paragraph(post_info[])
md.add_horizontal_rule()
content_sections = post_info.get(, [])
section content_sections:
section.get():
md.add_heading(section[], section.get(, ))
section.get():
md.add_paragraph(section[])
section.get():
md.add_code_block(
section[],
section.get(, )
)
section.get():
img = section[]
md.add_image(
img.get(, ),
img.get(, ),
img.get(, )
)
section.get():
md.add_list(section[], section.get(, ))
post_info.get():
md.add_heading(, )
md.add_paragraph(post_info[])
md
:
() -> :
:
markdown
extensions = [, , , ]
markdown.markdown(markdown_content, extensions=extensions)
ImportError:
():
:
weasyprint
html_content = MarkdownConverter.to_html(markdown_content)
css_style =
html_doc =
weasyprint.HTML(string=html_doc).write_pdf(output_path)
ImportError:
()
():
()
( * )
project_info = {
: ,
: ,
: ,
: [
,
],
: {
: ,
:
},
: [
{
: ,
: ,
:
}
],
:
}
readme_md = DocumentTemplate.create_readme_template(project_info)
readme_md.save_to_file()
()
api_info = {
: ,
: {
: ,
: ,
:
},
: {
: ,
: ,
:
},
: [
{
: ,
: ,
: ,
: [
{
: ,
: ,
: ,
: ,
:
}
],
: {
: ,
:
}
}
]
}
api_md = DocumentTemplate.create_api_documentation(api_info)
api_md.save_to_file()
()
blog_info = {
: ,
: ,
: ,
: ,
: [, , ],
: ,
: [
{
: ,
: ,
:
},
{
: ,
: ,
: ,
: ,
:
}
],
:
}
blog_md = DocumentTemplate.create_blog_post(blog_info)
blog_md.save_to_file()
()
html_content = MarkdownConverter.to_html(readme_md.render())
(, , encoding=) f:
f.write(html_content)
()
()
__name__ == :
main()
Markdown分析器
class MarkdownAnalyzer:
"""Markdown分析器"""
def __init__(self):
self.element_patterns = {
'heading': re.compile(r'^(#{1,6})\s+(.+)$'),
'list': re.compile(r'^(\s*)([-*+]|\d+\.)\s+(.+)$'),
'code_block': re.compile(r'^```(\w*)\n(.*?)\n```$', re.MULTILINE | re.DOTALL),
'image': re.compile(r'!\[([^\]]*)\]\(([^)]+)\)'),
'link': re.compile(r'\[([^\]]+)\]\(([^)]+)\)'),
'table': re.compile(r'^\|(.+)\|\n\|[-\s\|]+\|\n((?:\|.+\|\n?)*)', re.MULTILINE)
}
def analyze(self, markdown_content: str) -> Dict[str, Any]:
"""分析Markdown内容"""
lines = markdown_content.split('\n')
analysis = {
'total_lines': len(lines),
'total_characters': len(markdown_content),
'elements': {
'headings': [],
'lists': [],
'code_blocks': [],
'images': [],
'links': [],
'tables': []
},
: {},
: []
}
i, line (lines, ):
element_info = ._analyze_line(line, i)
element_info:
analysis[].append(element_info)
element_type = element_info[]
element_type analysis[]:
analysis[][element_type].append(element_info)
analysis[] = ._calculate_statistics(analysis[])
analysis
() -> [[, ]]:
line = line.rstrip()
heading_match = .element_patterns[].(line)
heading_match:
level = (heading_match.group())
text = heading_match.group()
{
: ,
: line_number,
: level,
: text,
: ._generate_anchor(text)
}
list_match = .element_patterns[].(line)
list_match:
indent = (list_match.group())
marker = list_match.group()
text = list_match.group()
ordered = marker.endswith()
{
: ,
: line_number,
: indent,
: ordered,
: text
}
line line.strip():
{
: ,
: line_number,
: line
}
() -> [, ]:
stats = {}
headings = elements[]
stats[] = {
: (headings),
: {}
}
heading headings:
level = heading[]
stats[][][level] = stats[][].get(level, ) +
lists = elements[]
stats[] = {
: (lists),
: ( lst lists lst[]),
: ( lst lists lst[])
}
element_type [, , , ]:
stats[element_type] = (elements[element_type])
stats
() -> :
re
anchor = re.sub(, , text.lower())
anchor = re.sub(, , anchor)
anchor.strip()
() -> :
analysis = .analyze(markdown_content)
headings = analysis[][]
toc_lines = []
heading headings:
heading[] <= max_level:
indent = * (heading[] - )
toc_lines.append()
.join(toc_lines)
():
analyzer = MarkdownAnalyzer()
()
__name__ == :
main()
Markdown最佳实践
文档结构
- 层次清晰: 合理使用标题层级
- 逻辑有序: 内容按逻辑顺序组织
- 导航友好: 提供目录和锚点
- 易于扫描: 使用列表和表格
内容质量
- 简洁明了: 避免冗长描述
- 示例丰富: 提供充分的代码示例
- 图文并茂: 适当使用图片和图表
- 及时更新: 保持文档与代码同步
格式规范
- 一致性: 保持格式风格统一
- 可读性: 合理使用空行和缩进
- 链接有效: 确保所有链接可访问
- 代码规范: 使用语法高亮
Markdown工具推荐
编辑器
- Typora: 所见即所得编辑器
- Mark Text: 开源Markdown编辑器
- Obsidian: 知识管理工具
- Notion: 集成文档平台
转换工具
- Pandoc: 通用文档转换器
- Marp: Markdown到PPT
- Hugo: 静态网站生成器
- Jekyll: GitHub Pages支持
扩展语法
- Mermaid: 图表和流程图
- PlantUML: UML图表
- KaTeX: 数学公式
- GitHub Flavored Markdown: 扩展语法
相关技能
- technical-writing - 技术写作
- documentation - 文档管理
- content-management - 内容管理
- web-development - Web开发
- api-documentation - API文档
- blog-writing - 博客写作