Domanda

Sto cercando di ottenere un blocco di linee tra 2 linee conosciute utilizzando pyparsing. Ad esempio:

ABC
....
DEF

Il mio codice 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)

-> ma non funziona. Python solo si blocca. Qualcuno mi può mostrare come fare?

Grazie,

È stato utile?

Soluzione 2

Finalmente ho trovato risposta alla mia domanda.

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)

che funziona per me.

Altri suggerimenti

Aggiungi questo codice di debug al vostro programma:

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

e il cambiamento searchString a parseString. setDebug () stamperà ogni volta un'espressione sta per essere tentato di partita, e se abbinati, quello ottenuto abbinati, e se non abbinato, l'eccezione. Con il vostro programma, dopo aver apportato queste modifiche ottengo:

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)

Probabilmente non è quello che ti aspettavi.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top