如何使用 python-markdown 从 Markdown 文件中获取元数据?

WoJ*_*WoJ 1 python markdown python-3.x

我正在尝试使用python-markdown从以下文件中提取元数据:

---
title: this is the title and it is compulsory
tags: this part is optional
something: this is not interesting, only 'title' and 'tags' is
---
some content
Run Code Online (Sandbox Code Playgroud)

元数据的文档给出了两个示例:

markdown.markdown(some_text, extensions=['meta'])
Run Code Online (Sandbox Code Playgroud)

>>> md = markdown.Markdown(extensions = ['meta'])
>>> html = md.convert(text)
>>> # Meta-data has been stripped from output
>>> print html
<p>This is the first paragraph of the document.</p>

>>> # View meta-data
>>> print md.Meta
{
'title' : ['My Document'],
'summary' : ['A brief description of my document.'],
'authors' : ['Waylan Limberg', 'John Doe'],
'date' : ['October 2, 2007'],
'blank-value' : [''],
'base_url' : ['http://example.com']
}
Run Code Online (Sandbox Code Playgroud)

我无法从这些示例中弄清楚如何实际获取元数据:

  • 第一个示例返回一个str,它当然不具有该Meta属性
  • 第二个示例不加载text,除了html(不用于提取元数据)。

WoJ*_*WoJ 5

我发现它:就地md.convert()工作(换句话说,修改)。md

代码

data = pathlib.Path(note).read_text(encoding='utf-8')
md = markdown.Markdown(extensions=['meta'])
md.convert(data)
print(md.Meta)
Run Code Online (Sandbox Code Playgroud)

将正确输出文件中的元数据note