473,699 Members | 2,149 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

help with pyparsing

-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

All,

I have the following lines that I would like to parse in python using
pyparsing, but have some problems forming the grammar.

Line in file:
table <ALINKconst { 207.135.103.128/26, 207.135.112.64/29 }
table <INTRANETpersis t { ! 10.200.2/24, 10.200/22 }
table <RFC_1918cons t { 192.168/16, ! 172.24.1/29, 172.16/12, 169.254/16 }
table <DIALERpersis t { 10.202/22 }
table <RAVPNconst { 10.206/22 }
table <KSconst { \
10.205.1/24, \
169.136.241.68, \
169.136.241.70, \
169.136.241.71, \
169.136.241.72, \
169.136.241.75, \
169.136.241.76, \
169.136.241.77, \
169.136.241.78, \
169.136.241.79, \
169.136.241.81, \
169.136.241.82, \
169.136.241.85 }

I have the following grammar defn.

tableName = Word(alphanums + "-" + "_")
leftClose = Suppress("<")
rightClose = Suppress(">")
key = Suppress("table ")
tableType = Regex("persist| const")
ip4Address = OneOrMore(Word( nums + "."))
ip4Network = Group(ip4Addres s + Optional(Word("/") +
OneOrMore(Word( nums))))
temp = ZeroOrMore("\\" + "\n")
tableList = OneOrMore(Optio nal("\\") |
ip4Network | ip4Address | Suppress(",") | Literal("!"))
leftParen = Suppress("{")
rightParen = Suppress("}")

table = key + leftClose + tableName + rightClose + tableType + \
leftParen + tableList + rightParen

I cannot seem to match sixth line in the file above, i.e table name with
KS, how do I form the grammar for it, BTW, I still cannot seem to ignore
comments using table.ignore(Li teral("#") + restOfLine), I get a parse error.

Any help appreciated.
Thanks
Prabhu
- -
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.4-svn0 (GNU/Linux)
Comment: Using GnuPG with SUSE - http://enigmail.mozdev.org

iD8DBQFHXMhFTkj paeKzB9YRAmZYAJ 9Lyys6+xCrGEsyy 33AoRWVdUOXQwCf TG9Q
/f7JZ2pAW6WDSzs7 9jbDFQE=
=CGb0
-----END PGP SIGNATURE-----
Dec 10 '07 #1
3 2514
On Dec 10, 7:01 am, Prabhu Gurumurthy <pguru...@gmail .comwrote:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

All,

I have the following lines that I would like to parse in python using
pyparsing, but have some problems forming the grammar.

Line in file:
table <ALINKconst { 207.135.103.128/26, 207.135.112.64/29 }
table <INTRANETpersis t { ! 10.200.2/24, 10.200/22 }
table <RFC_1918cons t { 192.168/16, ! 172.24.1/29, 172.16/12, 169.254/16 }
table <DIALERpersis t { 10.202/22 }
table <RAVPNconst { 10.206/22 }
table <KSconst { \
10.205.1/24, \
169.136.241.68, \
169.136.241.70, \
169.136.241.71, \
169.136.241.72, \
169.136.241.75, \
169.136.241.76, \
169.136.241.77, \
169.136.241.78, \
169.136.241.79, \
169.136.241.81, \
169.136.241.82, \
169.136.241.85 }

I have the following grammar defn.

tableName = Word(alphanums + "-" + "_")
leftClose = Suppress("<")
rightClose = Suppress(">")
key = Suppress("table ")
tableType = Regex("persist| const")
ip4Address = OneOrMore(Word( nums + "."))
ip4Network = Group(ip4Addres s + Optional(Word("/") +
OneOrMore(Word( nums))))
temp = ZeroOrMore("\\" + "\n")
tableList = OneOrMore(Optio nal("\\") |
ip4Network | ip4Address | Suppress(",") | Literal("!"))
leftParen = Suppress("{")
rightParen = Suppress("}")

table = key + leftClose + tableName + rightClose + tableType + \
leftParen + tableList + rightParen

I cannot seem to match sixth line in the file above, i.e table name with
KS, how do I form the grammar for it, BTW, I still cannot seem to ignore
comments using table.ignore(Li teral("#") + restOfLine), I get a parse error.

Any help appreciated.
Thanks
Prabhu
- -
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.4-svn0 (GNU/Linux)
Comment: Using GnuPG with SUSE -http://enigmail.mozdev .org

iD8DBQFHXMhFTkj paeKzB9YRAmZYAJ 9Lyys6+xCrGEsyy 33AoRWVdUOXQwCf TG9Q
/f7JZ2pAW6WDSzs7 9jbDFQE=
=CGb0
-----END PGP SIGNATURE-----
Shouldn't tableList be 'ZeroOrMore' instead...
Dec 10 '07 #2
On Dec 9, 11:01 pm, Prabhu Gurumurthy <pguru...@gmail .comwrote:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

All,

I have the following lines that I would like to parse in python using
pyparsing, but have some problems forming the grammar.

Line in file:
table <ALINKconst { 207.135.103.128/26, 207.135.112.64/29 }
table <INTRANETpersis t { ! 10.200.2/24, 10.200/22 }
table <RFC_1918cons t { 192.168/16, ! 172.24.1/29, 172.16/12, 169.254/16 }
table <DIALERpersis t { 10.202/22 }
table <RAVPNconst { 10.206/22 }
table <KSconst { \
10.205.1/24, \
169.136.241.68, \
169.136.241.70, \
169.136.241.71, \
169.136.241.72, \
169.136.241.75, \
169.136.241.76, \
169.136.241.77, \
169.136.241.78, \
169.136.241.79, \
169.136.241.81, \
169.136.241.82, \
169.136.241.85 }

I have the following grammar defn.

tableName = Word(alphanums + "-" + "_")
leftClose = Suppress("<")
rightClose = Suppress(">")
key = Suppress("table ")
tableType = Regex("persist| const")
ip4Address = OneOrMore(Word( nums + "."))
ip4Network = Group(ip4Addres s + Optional(Word("/") +
OneOrMore(Word( nums))))
temp = ZeroOrMore("\\" + "\n")
tableList = OneOrMore(Optio nal("\\") |
ip4Network | ip4Address | Suppress(",") | Literal("!"))
leftParen = Suppress("{")
rightParen = Suppress("}")

table = key + leftClose + tableName + rightClose + tableType + \
leftParen + tableList + rightParen

I cannot seem to match sixth line in the file above, i.e table name with
KS, how do I form the grammar for it, BTW, I still cannot seem to ignore
comments using table.ignore(Li teral("#") + restOfLine), I get a parse error.

Any help appreciated.
Thanks
Prabhu
Prabhu -

This is a good start, but here are some suggestions:

1. ip4Address = OneOrMore(Word( nums + "."))

Word(nums+".") will read any contiguous set of characters in the
string nums+".", so OneOrMore is not necessary for reading in an
ip4Address. Just use:

ip4Address = Word(nums + ".")
2. ip4Network = Group(ip4Addres s + Optional(Word("/") +
OneOrMore(Word( nums))))

Same comment, OneOrMore is not needed for the added value to the
ip4Address:

ip4Network = Group(ip4Addres s + Optional(Word("/") + Word(nums))))
3. tableList = OneOrMore(Optio nal("\\") |
ip4Network | ip4Address | Suppress(",") |
Literal("!"))

The list of ip4Networks is just a comma-delimited list, with some
entries preceded with a '!' character. It is simpler to use
pyparsing's built-in helper, delimitedList, as in:

tableList = Group( delimitedList(G roup("!"+ip4Net work)|ip4Networ k) )
Yes, I know, you are saying, "but what about all those backslashes?"
The backslashes look like they are just there as line continuations.
We can define an ignore expression, so that the table expression, and
all of its contained expressions, will ignore '\' characters as line
continuations:

table.ignore( Literal("\\") + LineEnd() )

And I'm not sure why you had trouble with ignoring '#' + restOfLine,
it works fine in the program below.

If you make these changes, your program will look something like this:

tableName = Word(alphanums + "-" + "_")
leftClose = Suppress("<")
rightClose = Suppress(">")
key = Suppress("table ")
tableType = Regex("persist| const")
ip4Address = Word(nums + ".")
ip4Network = Group(ip4Addres s + Optional(Word("/") + Word(nums)))
tableList = Group(delimited List(Group("!"+ ip4Network)|ip4 Network))
leftParen = Suppress("{")
rightParen = Suppress("}")

table = key + leftClose + tableName + rightClose + tableType + \
leftParen + tableList + rightParen
table.ignore(Li teral("\\") + LineEnd())
table.ignore(Li teral("#") + restOfLine)

# parse the input line, and pprint the results
result = OneOrMore(table ).parseString(l ine)
from pprint import pprint
pprint(result.a sList())

Prints out:
['ALINK',
'const',
[['207.135.103.12 8', '/', '26'], ['207.135.112.64 ', '/', '29']],
'INTRANET',
'persist',
[['!', ['10.200.2', '/', '24']], ['10.200', '/', '22']],
'RFC_1918',
'const',
[['192.168', '/', '16'],
['!', ['172.24.1', '/', '29']],
['172.16', '/', '12'],
['169.254', '/', '16']],
'DIALER',
'persist',
[['10.202', '/', '22']],
'RAVPN',
'const',
[['10.206', '/', '22']],
'KS',
'const',
[['10.205.1', '/', '24'],
['169.136.241.68 '],
['169.136.241.70 '],
['169.136.241.71 '],
['169.136.241.72 '],
['169.136.241.75 '],
['169.136.241.76 '],
['169.136.241.77 '],
['169.136.241.78 '],
['169.136.241.79 '],
['169.136.241.81 '],
['169.136.241.82 '],
['169.136.241.85 ']]]

-- Paul
Dec 10 '07 #3
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Paul McGuire wrote:
On Dec 9, 11:01 pm, Prabhu Gurumurthy <pguru...@gmail .comwrote:
>-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

All,

I have the following lines that I would like to parse in python using
pyparsing, but have some problems forming the grammar.

Line in file:
table <ALINKconst { 207.135.103.128/26, 207.135.112.64/29 }
table <INTRANETpersis t { ! 10.200.2/24, 10.200/22 }
table <RFC_1918cons t { 192.168/16, ! 172.24.1/29, 172.16/12, 169.254/16 }
table <DIALERpersis t { 10.202/22 }
table <RAVPNconst { 10.206/22 }
table <KSconst { \
10.205.1/24, \
169.136.241.68, \
169.136.241.70, \
169.136.241.71, \
169.136.241.72, \
169.136.241.75, \
169.136.241.76, \
169.136.241.77, \
169.136.241.78, \
169.136.241.79, \
169.136.241.81, \
169.136.241.82, \
169.136.241.85 }

I have the following grammar defn.

tableName = Word(alphanums + "-" + "_")
leftClose = Suppress("<")
rightClose = Suppress(">")
key = Suppress("table ")
tableType = Regex("persist| const")
ip4Address = OneOrMore(Word( nums + "."))
ip4Network = Group(ip4Addres s + Optional(Word("/") +
OneOrMore(Word (nums))))
temp = ZeroOrMore("\\" + "\n")
tableList = OneOrMore(Optio nal("\\") |
ip4Network | ip4Address | Suppress(",") | Literal("!"))
leftParen = Suppress("{")
rightParen = Suppress("}")

table = key + leftClose + tableName + rightClose + tableType + \
leftParen + tableList + rightParen

I cannot seem to match sixth line in the file above, i.e table name with
KS, how do I form the grammar for it, BTW, I still cannot seem to ignore
comments using table.ignore(Li teral("#") + restOfLine), I get a parse error.

Any help appreciated.
Thanks
Prabhu

Prabhu -

This is a good start, but here are some suggestions:

1. ip4Address = OneOrMore(Word( nums + "."))

Word(nums+".") will read any contiguous set of characters in the
string nums+".", so OneOrMore is not necessary for reading in an
ip4Address. Just use:

ip4Address = Word(nums + ".")
2. ip4Network = Group(ip4Addres s + Optional(Word("/") +
OneOrMore(Word( nums))))

Same comment, OneOrMore is not needed for the added value to the
ip4Address:

ip4Network = Group(ip4Addres s + Optional(Word("/") + Word(nums))))
3. tableList = OneOrMore(Optio nal("\\") |
ip4Network | ip4Address | Suppress(",") |
Literal("!"))

The list of ip4Networks is just a comma-delimited list, with some
entries preceded with a '!' character. It is simpler to use
pyparsing's built-in helper, delimitedList, as in:

tableList = Group( delimitedList(G roup("!"+ip4Net work)|ip4Networ k) )
Yes, I know, you are saying, "but what about all those backslashes?"
The backslashes look like they are just there as line continuations.
We can define an ignore expression, so that the table expression, and
all of its contained expressions, will ignore '\' characters as line
continuations:

table.ignore( Literal("\\") + LineEnd() )

And I'm not sure why you had trouble with ignoring '#' + restOfLine,
it works fine in the program below.

If you make these changes, your program will look something like this:

tableName = Word(alphanums + "-" + "_")
leftClose = Suppress("<")
rightClose = Suppress(">")
key = Suppress("table ")
tableType = Regex("persist| const")
ip4Address = Word(nums + ".")
ip4Network = Group(ip4Addres s + Optional(Word("/") + Word(nums)))
tableList = Group(delimited List(Group("!"+ ip4Network)|ip4 Network))
leftParen = Suppress("{")
rightParen = Suppress("}")

table = key + leftClose + tableName + rightClose + tableType + \
leftParen + tableList + rightParen
table.ignore(Li teral("\\") + LineEnd())
table.ignore(Li teral("#") + restOfLine)

# parse the input line, and pprint the results
result = OneOrMore(table ).parseString(l ine)
from pprint import pprint
pprint(result.a sList())

Prints out:
['ALINK',
'const',
[['207.135.103.12 8', '/', '26'], ['207.135.112.64 ', '/', '29']],
'INTRANET',
'persist',
[['!', ['10.200.2', '/', '24']], ['10.200', '/', '22']],
'RFC_1918',
'const',
[['192.168', '/', '16'],
['!', ['172.24.1', '/', '29']],
['172.16', '/', '12'],
['169.254', '/', '16']],
'DIALER',
'persist',
[['10.202', '/', '22']],
'RAVPN',
'const',
[['10.206', '/', '22']],
'KS',
'const',
[['10.205.1', '/', '24'],
['169.136.241.68 '],
['169.136.241.70 '],
['169.136.241.71 '],
['169.136.241.72 '],
['169.136.241.75 '],
['169.136.241.76 '],
['169.136.241.77 '],
['169.136.241.78 '],
['169.136.241.79 '],
['169.136.241.81 '],
['169.136.241.82 '],
['169.136.241.85 ']]]

-- Paul
Awesome, thanks a lot will try it today and will let you know how it
proceeds.

thanks again.
Prabhu
- -
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.4-svn0 (GNU/Linux)
Comment: Using GnuPG with SUSE - http://enigmail.mozdev.org

iD8DBQFHXWOQTkj paeKzB9YRAq/aAJ9b0uocbP+1Xx IVj4LgS76uFEuQH wCgxojY
zv05Raaj5McSEzD WXiSxf9c=
=MMFV
-----END PGP SIGNATURE-----
Dec 10 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
2913
by: RiGGa | last post by:
Hi, I want to parse a web page in Python and have it write certain values out to a mysql database. I really dont know where to start with parsing the html code ( I can work out the database part ). I have had a look at htmllib but I need more info. Can anyone point me in the right direction , a tutorial or something would be great. Many thanks
5
2353
by: Lukas Holcik | last post by:
Hi everyone! How can I simply search text for regexps (lets say <a href="(.*?)">(.*?)</a>) and save all URLs(1) and link contents(2) in a dictionary { name : URL}? In a single pass if it could. Or how can I replace the html &entities; in a string "blablabla&amp;blablabal&amp;balbalbal" with the chars they mean using re.sub? I found out they are stored in an dict . I though about this functionality:
15
2024
by: kpp9c | last post by:
I am kind of in a bit of a jam (okay a big jam) and i was hoping that someone here could give me a quick hand. I had a few pages of time calculations to do. So, i just started in on them typing them in my time calculator and writing them in by hand. Now i realize, that i really need a script to do this because: 1. It turns out there are hundreds of pages of this stuff. 2. I have to do something similar in again soon. 3. By doing it by...
8
1683
by: rh0dium | last post by:
Hi all, I am using python to drive another tool using pexpect. The values which I get back I would like to automatically put into a list if there is more than one return value. They provide me a way to see that the data is in set by parenthesising it. This is all generated as I said using pexpect - Here is how I use it.. child = pexpect.spawn( _buildCadenceExe(), timeout=timeout) child.sendline("somefunction()")
5
1322
by: Dave | last post by:
OK, I'm stumped. I'm trying to find newline characters (\n, specifically) that are NOT in comments. So, for example (where "<-" = a newline character): ========================================== 1: <- 2: /*<- 3: ----------------------<-
6
1661
by: GHUM | last post by:
I need to split a text at every ; (Semikolon), but not at semikolons which are "escaped" within a pair of $$ or $_$ signs. My guess was that something along this should happen withing csv.py; but ... it is done within _csv.c :( Example: the SQL text should be splitted at "<split here>" (of course, those "split heres" are not there yet :) set interval 2;
1
2644
by: Steve | last post by:
Hi All (especially Paul McGuire!) Could you lend a hand in the grammar and paring of the output from the function win32pdhutil.ShowAllProcesses()? This is the code that I have so far (it is very clumsy at the moment) : import string
1
353
by: Neal Becker | last post by:
I'm just trying out pyparsing. I get stack overflow on my first try. Any help? #/usr/bin/python from pyparsing import Word, alphas, QuotedString, OneOrMore, delimitedList first_line = '' def main():
7
2375
by: Donn Ingle | last post by:
Hi, I really hope someone can help me -- I'm stuck. I have written three versions of code over a week and still can't get past this problem, it's blocking my path to getting other code written. This might be a little hairy, but I'll try to keep it short. Situation: I want to pass a string to a function which will parse it and generate objects in a list.
5
1487
by: Paul McGuire | last post by:
I've just uploaded to SourceForge and PyPI the latest update to pyparsing, version 1.5.1. It has been a couple of months since 1.5.0 was released, and a number of bug-fixes and enhancements have accumulated in SVN, so time for a release! Here's what's new in Pyparsing 1.5.1: - Added __dir__() methods to ParseBaseException and ParseResults, to support new dir() behavior in Py2.6 and Py3.0. If dir() is called on a ParseResults object,...
0
8694
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9182
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9041
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8928
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8890
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
6538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5877
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
2355
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2013
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.