You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

60 lines
2.0 KiB

import markdown_to_json
import json
def markdown_to_dict(markdown_content):
"""
将 Markdown 内容转换为 Python 字典
"""
# 将 Markdown 转换为 JSON 字符串
json_content = markdown_to_json.jsonify(markdown_content)
# 解码 Unicode 转义
json_content = json_content.encode('utf-8').decode('unicode_escape')
# 将 JSON 字符串转换为字典
return json.loads(json_content)
def extract_level1(json_dict):
"""
提取一级目录,生成指定格式的 JSON 对象列表
"""
# 获取第一个一级目录的名称
level1_title = next(iter(json_dict.keys()), None)
if level1_title:
return [{"type": "cover", "data": {"title": level1_title, "text": level1_title}}]
return []
def extract_level2(json_dict, level1_title=None):
"""
提取指定一级目录下的二级目录,生成指定格式的 JSON 对象列表
"""
# 如果没有指定一级目录,则使用第一个一级目录
if level1_title is None:
level1_title = next(iter(json_dict.keys()), None)
if level1_title and level1_title in json_dict:
return [{"type": "transition", "data": {"title": title, "text": title}} for title in
json_dict[level1_title].keys()]
return []
if __name__ == '__main__':
# 打开文本文件 Sample.md
with open("Sample.md", "r", encoding="utf-8") as file:
# 读取 Markdown 文件的内容
markdown_content = file.read()
# 将 Markdown 转换为字典
json_dict = markdown_to_dict(markdown_content)
# 提取一级目录
level1_json = extract_level1(json_dict)
print("一级目录:")
for item in level1_json:
print(json.dumps(item, ensure_ascii=False))
# 提取二级目录(自动获取一级目录名称)
level2_json = extract_level2(json_dict)
print("\n二级目录:")
for item in level2_json:
print(json.dumps(item, ensure_ascii=False))