gpt4 book ai didi

python - 对段落进行 Pyparsing

转载 作者:太空宇宙 更新时间:2023-11-03 15:54:21 24 4
gpt4 key购买 nike

我遇到了一个似乎无法解决的 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 解析标题行和缩进 block 的阶段。但我不能:

  • 将一个段落定义为应该连接的多行
  • 允许段落缩进

一个例子

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

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

关于python - 对段落进行 Pyparsing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44534653/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com