By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,922 Members | 1,493 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,922 IT Pros & Developers. It's quick & easy.

Pyparsing question

P: n/a
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
Jul 18 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a
"Khoa Nguyen" <KN*****@MEGISTO.com> wrote in message
news:ma************************************@python .org...
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']
Jul 18 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.