6

我正在尝试使用pyparsing解析可以使用反斜杠换行符组合(“ \\n”)分成多行的单词。这是我所做的:

from pyparsing import *

continued_ending = Literal('\\') + lineEnd
word = Word(alphas)
split_word = word + Suppress(continued_ending)
multi_line_word = Forward()
multi_line_word << (word | (split_word + multi_line_word))

print multi_line_word.parseString(
'''super\\
cali\\
fragi\\
listic''')

我得到的输出是['super'],而预期的输出是['super', 'cali', fragi', 'listic']。更好的是它们都作为一个词加入(我想我可以用multi_line_word.parseAction(lambda t: ''.join(t)).

我尝试在pyparsing helper中查看此代码,但它给了我一个错误,maximum recursion depth exceeded.

编辑 2009-11-15:我后来意识到 pyparsing 在空白方面有点慷慨,这导致了一些糟糕的假设,即我认为我正在解析的内容要宽松得多。也就是说,我们希望在单词、转义符和 EOL 字符的任何部分之间没有空格。

我意识到上面的小示例字符串作为测试用例是不够的,所以我编写了以下单元测试。通过这些测试的代码应该能够匹配我直觉上认为的转义拆分词——而且只是一个转义拆分词。它们不会匹配没有转义拆分的基本单词。我们可以——我相信应该——为此使用不同的语法结构。这使两者分开时保持整洁。

import unittest
import pyparsing

# Assumes you named your module 'multiline.py'
import multiline

class MultiLineTests(unittest.TestCase):

    def test_continued_ending(self):

        case = '\\\n'
        expected = ['\\', '\n']
        result = multiline.continued_ending.parseString(case).asList()
        self.assertEqual(result, expected)


    def test_continued_ending_space_between_parse_error(self):

        case = '\\ \n'
        self.assertRaises(
            pyparsing.ParseException,
            multiline.continued_ending.parseString,
            case
        )


    def test_split_word(self):

        cases = ('shiny\\', 'shiny\\\n', ' shiny\\')
        expected = ['shiny']
        for case in cases:
            result = multiline.split_word.parseString(case).asList()
            self.assertEqual(result, expected)


    def test_split_word_no_escape_parse_error(self):

        case = 'shiny'
        self.assertRaises(
            pyparsing.ParseException,
            multiline.split_word.parseString,
            case
        )


    def test_split_word_space_parse_error(self):

        cases = ('shiny \\', 'shiny\r\\', 'shiny\t\\', 'shiny\\ ')
        for case in cases:
            self.assertRaises(
                pyparsing.ParseException,
                multiline.split_word.parseString,
                case
            )


    def test_multi_line_word(self):

        cases = (
                'shiny\\',
                'shi\\\nny',
                'sh\\\ni\\\nny\\\n',
                ' shi\\\nny\\',
                'shi\\\nny '
                'shi\\\nny captain'
        )
        expected = ['shiny']
        for case in cases:
            result = multiline.multi_line_word.parseString(case).asList()
            self.assertEqual(result, expected)


    def test_multi_line_word_spaces_parse_error(self):

        cases = (
                'shi \\\nny',
                'shi\\ \nny',
                'sh\\\n iny',
                'shi\\\n\tny',
        )
        for case in cases:
            self.assertRaises(
                pyparsing.ParseException,
                multiline.multi_line_word.parseString,
                case
            )


if __name__ == '__main__':
    unittest.main()
4

2 回答 2

6

在四处闲逛之后,我发现了这个帮助线程,其中有一个值得注意的地方

当有人直接从 BNF 定义实现 pyparsing 语法时,我经常看到效率低下的语法。BNF 没有“一个或多个”或“零个或多个”或“可选”的概念......

有了这个,我有了改变这两行的想法

multi_line_word = Forward()
multi_line_word << (word | (split_word + multi_line_word))

multi_line_word = ZeroOrMore(split_word) + word

这让它输出我正在寻找的东西:['super', 'cali', fragi', 'listic'].

接下来,我添加了一个解析操作,它将这些标记连接在一起:

multi_line_word.setParseAction(lambda t: ''.join(t))

这给出了最终输出['supercalifragilistic']

我学到的带回家的信息是,一个人不会简单地走进魔多

只是在开玩笑。

带回家的信息是,不能简单地使用 pyparsing 实现 BNF 的一对一翻译。应该调用使用迭代类型的一些技巧。

编辑 2009-11-25:为了补偿更费力的测试用例,我将代码修改为以下内容:

no_space = NotAny(White(' \t\r'))
# make sure that the EOL immediately follows the escape backslash
continued_ending = Literal('\\') + no_space + lineEnd
word = Word(alphas)
# make sure that the escape backslash immediately follows the word
split_word = word + NotAny(White()) + Suppress(continued_ending)
multi_line_word = OneOrMore(split_word + NotAny(White())) + Optional(word)
multi_line_word.setParseAction(lambda t: ''.join(t))

这样做的好处是确保任何元素之间没有空格(转义反斜杠后的换行符除外)。

于 2009-11-15T04:10:18.857 回答
5

您与您的代码非常接近。这些mod中的任何一个都可以工作:

# '|' means MatchFirst, so you had a left-recursive expression
# reversing the order of the alternatives makes this work
multi_line_word << ((split_word + multi_line_word) | word)

# '^' means Or/MatchLongest, but beware using this inside a Forward
multi_line_word << (word ^ (split_word + multi_line_word))

# an unusual use of delimitedList, but it works
multi_line_word = delimitedList(word, continued_ending)

# in place of your parse action, you can wrap in a Combine
multi_line_word = Combine(delimitedList(word, continued_ending))

正如您在 pyparsing 谷歌搜索中发现的那样,BNF->pyparsing 翻译应该特别考虑使用 pyparsing 功能来代替 BNF,嗯,缺点。实际上,我正在撰写更长的答案,涉及更多 BNF 翻译问题,但是您已经找到了此材料(我假设在 wiki 上)。

于 2009-11-15T16:51:08.440 回答