Pyparsing for Paragraphs

时间:2017-06-14 02:56:11

标签: python parsing pyparsing

我遇到了pyparsing的一个小问题,我似乎无法解决。我想编写一条规则,为我解析多行段落。最终目标是以递归语法结束,它将解析如下内容:

Heading: awesome
    This is a paragraph and then
    a line break is inserted
    then we have more text

    but this is also a different line
    with more lines attached

    Other: cool
        This is another indented block
        possibly with more paragraphs

        This is another way to keep this up
        and write more things

    But then we can keep writing at the old level
    and get this

像HTML这样的东西:所以也许(当然使用解析树,我可以将其转换为我喜欢的任何格式)。

<Heading class="awesome">

    <p> This is a paragraph and then a line break is inserted and then we have more text </p>

    <p> but this is also a different line with more lines attached<p>

    <Other class="cool">
        <p> This is another indented block possibly with more paragraphs</p>
        <p> This is another way to keep this up and write more things</p>
    </Other>

    <p> But then we can keep writing at the old level and get this</p>
</Heading>

的进展

我已经设法进入可以解析标题行的阶段,以及使用pyparsing的缩进块。但我不能:

  • 将段落定义为应加入的多行
  • 允许段落缩进

示例

here开始,我可以将段落输出到单行,但似乎没有办法在不删除换行符的情况下将其转换为解析树。

我相信一段应该是:

words = ## I've defined words to allow a set of characters I need
lines = OneOrMore(words)
paragraph = OneOrMore(lines) + lineEnd

但这似乎对我不起作用。任何想法都很棒:)。

1 个答案:

答案 0 :(得分:3)

所以我设法解决了这个问题,对于任何在未来偶然发现这一点的人来说。您可以像这样定义段落。虽然它肯定不理想,但并不完全符合我所描述的语法。相关代码是:

line = OneOrMore(CharsNotIn('\n')) + Suppress(lineEnd)
emptyline = ~line
paragraph = OneOrMore(line) + emptyline
paragraph.setParseAction(join_lines)

join_lines定义为:

def join_lines(tokens):
    stripped = [t.strip() for t in tokens]
    joined = " ".join(stripped)
    return joined

如果这符合您的需要,那应该指向正确的方向:)我希望有所帮助!

更好的空行

上面给出的空行的定义绝对不是理想的,它可以得到显着改善。我发现的最好方法如下:

empty_line = Suppress(LineStart() + ZeroOrMore(" ") + LineEnd())
empty_line.setWhitespaceChars("")

这允许您使用空格填充空行,而不会破坏匹配。