【问题标题】:Pyparsing for ParagraphsPyparsing 段落
【发布时间】:2017-06-14 02:56:11
【问题描述】:

我在 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

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

【问题讨论】:

    标签: python parsing pyparsing


    【解决方案1】:

    所以我设法解决了这个问题,以供将来偶然发现此问题的任何人使用。您可以像这样定义段落。虽然它肯定不理想,并且与我描述的语法不完全匹配。相关代码为:

    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("")
    

    这允许您在不中断匹配的情况下使用空格填充空行。

    【讨论】:

      猜你喜欢
      • 2015-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-12
      • 2021-03-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多