python解析2条已知行之间的文本块

时间:2010-10-28 07:39:57

标签: python pyparsing

我试图使用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)

- >但它不起作用。 Python只是挂起。 谁能告诉我怎么做?

谢谢,

2 个答案:

答案 0 :(得分:1)

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

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)

可能不是你所期望的。

答案 1 :(得分:0)

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

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)

这适合我。