编程语言
首页 > 编程语言> > python-段落的Pyparsing

python-段落的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

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

解决方法:

因此,对于以后偶然发现此问题的任何人,我都设法解决了这一问题.您可以这样定义段落.尽管它当然不是理想的,并且与我描述的语法不完全匹配.相关代码为:

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

这使您可以在不中断匹配的情况下用空格填充空行.

标签:pyparsing,python,parsing
来源: https://codeday.me/bug/20191111/2018689.html