【问题标题】:Getting h1 from markdown via python's pandoc library通过 python 的 pandoc 库从 markdown 中获取 h1
【发布时间】:2022-01-12 10:13:26
【问题描述】:

我正在编写一个 python 批处理脚本来处理许多降价文件以获取类似 h1 的文本以生成“标题”元数据变量(我忘记将“标题”添加到 frontmatter 中)。我没有将它用作 pandoc 过滤器。

因此我想通过 pandoc-python 处理这些文件,但我对此并不熟悉,我无法弄清楚如何只获取 h1。

content = pandoc.read(post.content)

'content' 是 pandoc 原生格式。我看到了这样的东西

(Pdb) content                                                                                                                                                                                                                                 
Pandoc(Meta({}), [Header(1, ('foobar', [], []), [Str('foobar:')]), Para(...

我想将 h1 作为简单的文本。

【问题讨论】:

    标签: python markdown pandoc


    【解决方案1】:

    我有以下 sn-p 适用于带有 #======= 的标头。

    import pandoc
    from pandoc.types import *
    
    with open('README.md') as f:
        content = pandoc.read(f.read()) 
    # But you can use your content.
    headers = []
    
    for elt in pandoc.iter(content):
         if isinstance(elt, Header):
             if elt[0] == 1: # this is header 1, remove this if statement if you want all headers.
                 headers.append(elt[1][0])
    

    或者如果你想要大写的确切字符串等:

    for elt in pandoc.iter(content):
        if isinstance(elt, Header):
            if elt[0] == 1: # this is header 1, remove this if statement if you want all headers.
                header.append(pandoc.write(elt[-1]).strip())
    

    【讨论】:

    • 第一个 for 循环中的 var 似乎有错字,ele -> elt
    【解决方案2】:

    也可以尝试配置 pandoc 来为我们做这件事。以下是手册对--shift-heading-level-by 选项的说明:

    --shift-heading-level-by=号码

    将标题级别移动一个正整数或负整数。 例如,--shift-heading-level-by=-1,级别 2 标题变为 1 级标题和 3 级标题 成为 2 级标题。标题不能有级别 小于 1,因此标题将移至 1 级以下 成为常规段落。例外:-N 移位, 文档开头的 N 级标题 替换元数据标题。 --shift-heading-level-by=-1 在转换 HTML 或 Markdown 文档时是一个不错的选择 使用初始级别 1 标题作为文档标题和 2 级以上的章节标题。 --shift-heading-level-by=1 可能是转换 Markdown 文档的好选择 对 HTML 的部分使用 1 级标题,因为 pandoc 使用 用于呈现文档标题的 1 级标题。

    因此,使用--shift-heading-level-by=-1 运行 pandoc 可能足以满足您的需求。

    【讨论】:

    • 不。这些降价文件不在任何 pandoc 管理范围内,我只想通过 python 的 pandoc 库从降价内容中获取 h1。我会做的事情超出了 pandoc 范围。这里的重点是从 markdown 内容中提取一些内容,并将其用于 python 中的任何目的。
    猜你喜欢
    • 2016-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 2014-06-01
    • 1970-01-01
    相关资源
    最近更新 更多