Python:从markdown文件中获取json frontmatter

问题描述 投票:0回答:1

我想使用python3从静态站点生成器解析内容文件。这样的文件可以在文件开头的json,yaml或toml中有前导,然后是内容;如果它是yaml或toml,那么很容易获得前端,因为那些起始端以特定的字符串(---或+++)结尾。有没有办法从文件的开头将json对象转换为python json对象,将文件其余部分的内容转换为字符串?

这是一个基于hugo静态站点生成器的frontmatter example的文件示例:

{
   "categories": [
      "Development",
      "VIM"
   ],
   "date": "2012-04-06",
   "description": "spf13-vim is a cross platform distribution of vim plugins and resources for Vim.",
   "slug": "spf13-vim-3-0-release-and-new-website",
   "tags": [
      ".vimrc",
      "plugins",
      "spf13-vim",
      "vim"
   ],
   "title": "spf13-vim 3.0 release and new website"
}
# Et sed pronos letum minatur

## Hos promissa est induit ductae non tamen

Lorem markdownum est, peragentem nomine fugaeque terruit ista quantum constat
vicinia. Per lingua concita. *Receptus Sibylla* frustra, genitor praesensque
texta vitiatis traxere cum natura feram ducunt terram.

根据Python Regex to match YAML Front Matter的答案,我得到了这个:

matches = re.search(r'^\s*(\{.*\})\s*$(.*)', content, re.DOTALL|re.MULTILINE)

这基本上是有效的,但是在一行的开头的json部分下面的文本部分可能会有另一个闭合的花括号 - 并且它不能处理嵌套的json对象

python json
1个回答
0
投票

我也在寻找一种工具来做你所描述的,但我对不太原始的前端类型感兴趣,比如TOML和YAML。以下项目应该提供您所需要的。我还从项目的文档中提供了一些片段来演示这种行为。

Python Frontmatterdocs

使用YAML(或其他)前端解析和管理帖子

>>> post = frontmatter.load('tests/hello-world.markdown')
>>> print(post.content)
Well, hello there, world.
>>> print(post['title'])
Hello, world!
>>> print(frontmatter.dumps(post))
---
excerpt: tl;dr
layout: post
title: Hello, world!
---
Well, hello there, world.
© www.soinside.com 2019 - 2024. All rights reserved.