Pyparsing question

K

Khoa Nguyen

Hi,

I am a newbie to Python and pyparsing. I am having difficulty creating a
grammar that spans multiple lines, the input data look like this

RTSP/1.0 200 OK\r\n
Cseq: 1\r\n
Session: 12345-1\r\n
\r\n

Greatly appreciate if anyone can give me a sample or point me to the
right direction

Thanks,


Khoa Nguyen
 
P

Paul McGuire

Khoa Nguyen said:
Hi,

I am a newbie to Python and pyparsing. I am having difficulty creating a
grammar that spans multiple lines, the input data look like this

RTSP/1.0 200 OK\r\n
Cseq: 1\r\n
Session: 12345-1\r\n
\r\n

Greatly appreciate if anyone can give me a sample or point me to the
right direction

Thanks,


Khoa Nguyen
=========================
Khoa -

In general, pyparsing will ignore line breaks as whitespace. This data
could be parsed with as broad a grammar as:

response = Literal("RTSP") + restOfLine.setResultsName("RTSPline") + \
Literal("Cseq:") + restOfLine.setResultsName("CseqLine") + \
Literal("Session:") + restOfLine.setResultsName("SessionLine")

For more structure, enclose each line inside Group objects.
response = Group( Literal("RTSP") + restOfLine ).setResultsName("RTSPline")
+ \
Group( Literal("Cseq:") + restOfLine ).setResultsName("CseqLine") + \
Group( Literal("Session:") + restOfLine ).setResultsName("SessionLine")

Here is a working (and tested!) sample.

-- Paul


==========================

from pyparsing import Literal, restOfLine, Group

data = """RTSP/1.0 200 OK
Cseq: 1
Session: 12345-1

"""

print "========"
print data
print "========"

response = Literal("RTSP") + restOfLine.setResultsName("RTSPline") + \
Literal("Cseq:") + restOfLine.setResultsName("CseqLine") + \
Literal("Session:") + restOfLine.setResultsName("SessionLine")

respFields = response.parseString(data)
print respFields
for k in respFields.keys():
print k,"=",respFields[k]

===========================
Output:

========
RTSP/1.0 200 OK
Cseq: 1
Session: 12345-1


========
['RTSP', '/1.0 200 OK', 'Cseq:', ' 1', 'Session:', ' 12345-1']
SessionLine = 12345-1
RTSPline = /1.0 200 OK
CseqLine = 1
============================
Output (using Group'ed constructs):
========
RTSP/1.0 200 OK
Cseq: 1
Session: 12345-1


========
[['RTSP', '/1.0 200 OK'], ['Cseq:', ' 1'], ['Session:', ' 12345-1']]
SessionLine = ['Session:', ' 12345-1']
RTSPline = ['RTSP', '/1.0 200 OK']
CseqLine = ['Cseq:', ' 1']
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top