ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

python-段落的Pyparsing

2019-11-11 08:05:50  阅读:280  来源: 互联网

标签:pyparsing python parsing


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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有