代码之家  ›  专栏  ›  技术社区  ›  Sean Nguyen

python解析两行之间的文本块

  •  1
  • Sean Nguyen  · 技术社区  · 15 年前

    我正在尝试使用pyparsing在两个已知行之间获取一个行块。例如:

    ABC
    ....
    DEF
    

    我的Python代码:

    end = Literal("\n").suppress()
    firstLine = Literal("ABC") + SkipTo(end)
    secondLine = Literal("DEF") + SkipTo(end)
    line = SkipTo(end)
    test = firstLine + OneOrMore(line) + secondLine
    
    test.searchString(myText)
    

    --&但是它不起作用。巨蟒挂了。 有人能告诉我怎么做吗?

    谢谢,

    2 回复  |  直到 15 年前
        1
  •  1
  •   PaulMcG    15 年前

    将此调试代码添加到程序中:

    firstLine.setName("firstLine").setDebug()
    line.setName("line").setDebug()
    secondLine.setName("secondLine").setDebug()
    

    并将searchString更改为parseString。每次试图匹配表达式时,setdebug()都会打印出来,如果匹配,则会打印出匹配的内容,如果不匹配,则打印出异常。通过您的程序,在进行这些更改后,我得到:

    Match firstLine at loc 0(1,1)
    Matched firstLine -> ['ABC', '.... ']
    Match line at loc 11(3,1)
    Matched line -> ['DEF ']
    Match line at loc 15(3,1)
    Exception raised:Expected line (at char 17), (line:4, col:2)
    Match secondLine at loc 15(3,1)
    Exception raised:Expected "DEF" (at char 16), (line:4, col:1)
    Traceback (most recent call last):
      File "rrrr.py", line 19, in <module>
        test.parseString(myText) 
      File "C:\Python25\lib\site-packages\pyparsing-1.5.5-py...
        raise exc
    pyparsing.ParseException: Expected "DEF" (at char 16), (line:4, col:1)
    

    可能不是你所期望的。

        2
  •  0
  •   Sean Nguyen    15 年前

    我终于找到了我问题的答案。

    end = Literal("\n").suppress()
    firstLine = Literal("ABC") + SkipTo(end)
    secondLine = Literal("DEF") + SkipTo(end)
    line = ~secondLine + SkipTo(end)
    test = firstLine + OneOrMore(line) + secondLine
    
    test.searchString(myText)
    

    这对我很有用。