【问题标题】:Python: get json frontmatter from markdown filePython:从 Markdown 文件中获取 json frontmatter
【发布时间】:2018-09-06 11:45:58
【问题描述】:

我想使用 python3 解析来自静态站点生成器的内容文件。此类文件可以在文件开头和之后的内容中有 json、yaml 或 toml 中的 frontmatter;如果它是 yaml 或 toml,则很容易获得 frontmatter,因为它们以特定字符串(--- 或 +++)开头结尾。 有没有办法将文件开头的 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 对象

【问题讨论】:

  • 你能举个输入文件的例子吗?向我们展示您尝试过的代码,并告诉我们哪里出错了。
  • 添加了输入文件示例、代码和更详细的问题描述
  • 改进了正则表达式并澄清了该方法的问题
  • 你会在 json 前端问题之外有任何闭合花括号吗?如果没有,您可以简单地执行str.rfind 来定位最后一次出现的位置,然后对文本进行切片以获取 json。否则,您可以遍历右括号的位置并尝试加载 json;如果你得到一个 ValueError,请继续下一个事件。蛮力比较测试而不是正则表达式。

标签: python json


【解决方案1】:

我也在寻找一种工具来执行您所描述的操作,但我对不太原始的前端类型感兴趣,例如 TOML 和 YAML。以下项目应提供您所需要的。我还提供了项目文档中的一些 sn-ps 来演示该行为。

Python Frontmatter (docs)

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

>>> 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.

【讨论】:

    猜你喜欢
    • 2015-03-29
    • 2016-08-25
    • 2021-05-31
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 2021-06-23
    相关资源
    最近更新 更多