473,545 Members | 2,001 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Parsing files -- pyparsing to the rescue?

Hi all,

I have a file which I need to parse and I need to be able to break it
down by sections. I know it's possible but I can't seem to figure this
out.

The sections are broken by <> with one or more keywords in the <>.
What I want to do is to be able to pars a particular section of the
file. So for example I need to be able to look at the SYSLIB section.
Presumably the sections are
<SYSLIB>
Sys Data
Sys-Data
asdkData
Data
<LOGLVS>
Data
Data
Data
Data
<SOME SECTION>
Data
Data
Data
Data
<NETLIST>
Data
Data
Data
Data
<NET>

So if I wanted to break them down..

Sections are broken down by this..

secH=pyparsing. LineStart() + pyparsing.Suppr ess(
pyparsing.Liter al("<")) +
pyparsing.OneOr More(pyparsing. Word(pyparsing. alphanums)) +
pyparsing.Suppr ess( pyparsing.Liter al(">"))

But how do I say that <SECTIONn> stops at the start of the next
<SECTIONm>?

Jan 16 '06 #1
3 1985
rh0dium wrote:
I have a file which I need to parse and I need to be able to break it
down by sections. I know it's possible but I can't seem to figure this
out.

The sections are broken by <> with one or more keywords in the <>.
What I want to do is to be able to pars a particular section of the
file. So for example I need to be able to look at the SYSLIB section.
Presumably the sections are
<SYSLIB>
Sys Data
Sys-Data
asdkData
Data
<LOGLVS>
Data
Data
Data
Data
<SOME SECTION>
Data
Data
Data
Data
<NETLIST>
Data
Data
Data
Data
<NET>


Given your description, pyparsing doesn't feel like the correct tool:

secs = {}
for L in file("foo.txt", "rU"):
L = L.rstrip("\n")
if re.match(r"<.*> ", L):
name = L[1:-1]
secs[name] = []
else:
secs[name].append(L)

--
Giovanni Bajo
Jan 16 '06 #2
"rh0dium" <sk****@pointci rcle.com> wrote in message
news:11******** *************@g 47g2000cwa.goog legroups.com...
Hi all,

I have a file which I need to parse and I need to be able to break it
down by sections. I know it's possible but I can't seem to figure this
out.

The sections are broken by <> with one or more keywords in the <>.
But how do I say that <SECTIONn> stops at the start of the next
<SECTIONm>?


See the attached working example - the comments and definition of dataLine
show how this is done.

This is something of a trick in pyparsing, but it is a basic characteristic
of the pyparsing recursive descent parser.

-- Paul

data="""<SYSLIB >
Sys Data
Sys-Data
asdkData
Data
<LOGLVS>
Data
Data
Data
Data
<SOME SECTION>
Data
Data
Data
Data
<NETLIST>
Data
Data
Data
Data
<NET>
"""

from pyparsing import *

# basic pyparsing version
secLabel = Suppress("<") + OneOrMore(Word( alphas)) + Suppress(">") +
LineEnd().suppr ess()
# need to indicate which entries are *not* valid datalines - next secLabel,
or end of string
dataLine = ~secLabel + ~StringEnd() + restOfLine + LineEnd().suppr ess()

# a data section is a section label, followed by zero or more data lines
section = Group(secLabel + ZeroOrMore(data Line))

# a config data contains one or more sections
configData = OneOrMore(secti on)

# parse the input data and print the results
res = configData.pars eString(data)
print res

# prints:
# [['SYSLIB', 'Sys Data', 'Sys-Data', 'asdkData', 'Data'], ['LOGLVS',
'Data', 'Data', 'Data', 'Data'], ['SOME', 'SECTION', 'Data', 'Data', 'Data',
'Data'], ['NETLIST', 'Data', 'Data', 'Data', 'Data'], ['NET']]
# enhanced version, constructing a ParseResults with dict-like access
# (reuses previous expression definitions)

# combine multiword keys into a single string
# - want <SOME SECTION> to return 'SOME SECTION', not
# 'SOME', 'SECTION'
def joinKeyWords(s, l,t):
return " ".join(t)
secLabel.setPar seAction(joinKe yWords)
section = Group(secLabel + ZeroOrMore(data Line))
configData = Dict(OneOrMore( section))

# parse the input data, and access the results by section name
res = configData.pars eString(data)
print res
print res["SYSLIB"]
print res["SOME SECTION"]
print res.keys()
# prints:
#[['SYSLIB', 'Sys Data', 'Sys-Data', 'asdkData', 'Data'], ['LOGLVS', 'Data',
'Data', 'Data', 'Data'], ['SOME SECTION', 'Data', 'Data', 'Data', 'Data'],
['NETLIST', 'Data', 'Data', 'Data', 'Data'], ['NET']]
#['Sys Data', 'Sys-Data', 'asdkData', 'Data']
#['Data', 'Data', 'Data', 'Data']
#['LOGLVS', 'NET', 'NETLIST', 'SYSLIB', 'SOME SECTION']

Jan 17 '06 #3
Try this

code
=====
import re
p = re.compile(r'<S YSLIB>([^<]*)<')
s = open("file").re ad()
m = re.search(p, s)
if m: res = m.groups()[0]
res = res.lstrip("\n" )
res = res.rstrip("\n" )
print res
result:
=======
%python parser.py
Sys Data
Sys-Data
asdkData
Data
%

Thanks
Allan
"rh0dium" <sk****@pointci rcle.com> wrote in message
news:11******** *************@g 47g2000cwa.goog legroups.com...
Hi all,

I have a file which I need to parse and I need to be able to break it
down by sections. I know it's possible but I can't seem to figure this
out.

The sections are broken by <> with one or more keywords in the <>.
What I want to do is to be able to pars a particular section of the
file. So for example I need to be able to look at the SYSLIB section.
Presumably the sections are
<SYSLIB>
Sys Data
Sys-Data
asdkData
Data
<LOGLVS>
Data
Data
Data
Data
<SOME SECTION>
Data
Data
Data
Data
<NETLIST>
Data
Data
Data
Data
<NET>

So if I wanted to break them down..

Sections are broken down by this..

secH=pyparsing. LineStart() + pyparsing.Suppr ess(
pyparsing.Liter al("<")) +
pyparsing.OneOr More(pyparsing. Word(pyparsing. alphanums)) +
pyparsing.Suppr ess( pyparsing.Liter al(">"))

But how do I say that <SECTIONn> stops at the start of the next
<SECTIONm>?

Jan 17 '06 #4

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

Similar topics

9
2905
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. ...
8
5687
by: Bram Stolk | last post by:
Hi there, What could I use to parse CPP macros in Python? I tried the Parnassus Vaults, and python lib docs, but could not find a suitable module. Thanks, Bram
6
8689
by: Ian McConnell | last post by:
I've got a header file which lists a whole load of C functions of the form int func1(float *arr, int len, double arg1); int func2(float **arr, float *arr2, int len, double arg1, double arg2); It's a numerical library so all functions return an int and accept varying combinations of float pointers, ints and doubles. What's the easiest...
9
4046
by: ankitdesai | last post by:
I would like to parse a couple of tables within an individual player's SHTML page. For example, I would like to get the "Actual Pitching Statistics" and the "Translated Pitching Statistics" portions of Babe Ruth page (http://www.baseballprospectus.com/dt/ruthba01.shtml) and store that info in a CSV file. Also, I would like to do this for...
3
2692
by: aspineux | last post by:
My goal is to write a parser for these imaginary string from the SMTP protocol, regarding RFC 821 and 1869. I'm a little flexible with the BNF from these RFC :-) Any comment ? tests= def RN(name, regex): """protect using () and give an optional name to a regex""" if name:
5
1307
by: tool69 | last post by:
Hi, I need to parse some source with nested parenthesis, like this : { {item1} { {item2} {item3}
3
4229
by: Phillip B Oldham | last post by:
Hi. I'm stretching my boundaries in programming with a little python shell-script which is going to loop through a list of domain names, grab the whois record, parse it, and put the results into a csv. I've got the results coming back fine, but since I have *no* experience with python I'm wondering what would be the preferred "pythonic" way...
4
3157
by: Alan G Isaac | last post by:
Can anyone recommend a pure Python parser of BibTeX files? Ideally MIT or BSD licensed? Online search some possibilities: http://svn.plone.org/svn/collective/bibliograph.parsing/trunk/bibliograph/parsing/parsers/bibtex.py http://www.geocities.com/fiolj/bibtexparse.html http://www.cis.udel.edu/~sprenkle/bibtex2html/bibtex2xml.py Despite the...
2
1900
by: =?ISO-8859-1?Q?Andr=E9?= | last post by:
Hi everyone, I would like to implement a parser for a mini-language and would appreciate some pointers. The type of text I would like to parse is an extension of: http://www.websequencediagrams.com/examples.html For those that don't want to go to the link, consider the following, *very* simplified, example:
0
7479
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...
0
7669
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. ...
1
7439
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...
0
7773
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...
1
5343
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...
0
3468
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3450
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1901
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1028
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.