473,386 Members | 1,630 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Problem using Optional pyparsing

Hi,

I know this isnt the pyparsing list, but it doesnt seem like there is
one. I m trying to use pyparsing to parse a file however I cant get
the Optional keyword to work. My file generally looks like this:

ALIGNMENT 1020 YS2-10a02.q1k chr09 1295 42 141045
142297 C 1254 95.06 1295 reject_bad_break 0

or this:

ALIGNMENT 36 YS2-10a08.q1k chrm 208 165 10745
10788 C 44 95.45 593 reject_low 10,14

and my grammar work well for these lines, however somethings the row looks like:
ALIGNMENT 53 YS2-10b03.p1k chr12 180 125 1067465
1067520 C 56 98.21 532|5,2 reject_low 25

So I try to parse the 532 using

from pyparsing import *

integer = Word( nums )
float = Word( nums+".")
identifier = Word( alphanums+"-_." )

alignment = Literal("ALIGNMENT ").suppress()
row_1 = integer.setResultsName("row_1")#.setParseAction(ma ke_int)
src_id = identifier.setResultsName("src_id")
dest_id = identifier.setResultsName("dest_id")
src_start = integer.setResultsName("src_start")#.setParseActio n(make_int)
src_stop = integer.setResultsName("src_stop")#.setParseAction (make_int)
dest_start = integer.setResultsName("dest_start")#.setParseActi on(make_int)
dest_stop = integer.setResultsName("dest_stop")#.setParseActio n(make_int)
row_8 = oneOf("F C").setResultsName("row_8")
length = integer.setResultsName("length")#.setParseAction(m ake_int)
percent_id = float.setResultsName("percent_id")#.setParseAction (make_float)
row_11 = integer + Optional(Literal("|") + commaSeparatedList )
)#.setResultsName("row_11")#.setParseAction(make_i nt)
result = Word(alphas+"_").setResultsName("result")
row_13 = commaSeparatedList.setResultsName("row_13")

def make_alilines_status_parser():
return alignment + row_1 + src_id + dest_id + src_start + src_stop
+ dest_start + dest_stop + row_8 + length + percent_id + row_11 +
result + row_13

def parse_alilines_status(ifile):
alilines = make_alilines_status_parser()
for l in ifile:
yield alilines.parseString( l )

However my parser always fails on lines of type 3. Does anyone know
why the Optional part is not working.

Many Thanks in advance

Nathan
Aug 16 '07 #1
2 1963
Nathan Harmston wrote:
I know this isnt the pyparsing list, but it doesnt seem like there is
one. I m trying to use pyparsing to parse a file however I cant get
the Optional keyword to work. My file generally looks like this:

ALIGNMENT *1020 *YS2-10a02.q1k chr09 * * 1295 * * * 42 * *141045
142297 * C * *1254 95.06 1295 reject_bad_break 0

or this:

ALIGNMENT *36 * *YS2-10a08.q1k chrm * * *208 * * *165 * * 10745
10788 * C * * *44 95.45 593 reject_low 10,14

and my grammar work well for these lines, however somethings the row looks
like:
ALIGNMENT *53 * *YS2-10b03.p1k chr12 * * *180 * * *125 * 1067465
1067520 * C * * *56 98.21 532|5,2 reject_low 25

So I try to parse the 532 using

from pyparsing import *

integer = Word( nums )
float = Word( nums+".")
identifier = Word( alphanums+"-_." )

alignment = Literal("ALIGNMENT ").suppress()
row_1 = integer.setResultsName("row_1")#.setParseAction(ma ke_int)
src_id = identifier.setResultsName("src_id")
dest_id = identifier.setResultsName("dest_id")
src_start = integer.setResultsName("src_start")#.setParseActio n(make_int)
src_stop = integer.setResultsName("src_stop")#.setParseAction (make_int)
dest_start =
integer.setResultsName("dest_start")#.setParseActi on(make_int)
dest_stop = integer.setResultsName("dest_stop")#.setParseActio n(make_int)
row_8 = oneOf("F C").setResultsName("row_8")
length = integer.setResultsName("length")#.setParseAction(m ake_int)
percent_id =
float.setResultsName("percent_id")#.setParseAction (make_float)
row_11 = integer + Optional(Literal("|") + commaSeparatedList )
)#.setResultsName("row_11")#.setParseAction(make_i nt)
result = Word(alphas+"_").setResultsName("result")
row_13 = commaSeparatedList.setResultsName("row_13")

def make_alilines_status_parser():
* * return alignment + row_1 + src_id + dest_id + src_start + src_stop
+ dest_start + dest_stop + row_8 + length + percent_id + row_11 +
result + row_13

def parse_alilines_status(ifile):
* * alilines = make_alilines_status_parser()
* * for l in ifile:
* * * * yield alilines.parseString( l )

However my parser always fails on lines of type 3. Does anyone know
why the Optional part is not working.
The commaSeparatedList includes the rest of the line into its last item:
>>commaSeparatedList.parseString("a,b c")
(['a', 'b c'], {})

You can fix this by defining your own delimitedList that doesnt accept
whitespace, e. g.:
>>delimitedList(Word(alphanums)).parseString("a, b c")
(['a', 'b'], {})

Peter

Aug 16 '07 #2
On Aug 16, 2:09 am, "Nathan Harmston" <ratchetg...@googlemail.com>
wrote:
Hi,

I know this isnt the pyparsing list, but it doesnt seem like there is
one. I m trying to use pyparsing to parse a file however I cant get
the Optional keyword to work.
<snip>

Thanks, Peter, your comments are dead-on.

Pyparsing-related posts crop up here every so often, usually with me
as the culprit. But to address your question, I've added a "Getting
Help" page to the pyparsing wiki, with links to the various mailing
lists and support pages on SourceForge. Fortunately, I don't think
this group minds an occasional trip down Pyparsing Lane (there've been
no serious complaints so far).

Some other suggestions/comments on your parser:
- Good use of results names. For debugging, you can print out the
parse results by using the dump() method - this gives you this kind of
output:
[1020, 'YS2-10a02.q1k', 'chr09', 1295, 42, 141045, 142297, 'C',
1254, 95.060000000000002, 1295, 'reject_bad_break', '0']
- dest_id: chr09
- dest_start: 141045
- dest_stop: 142297
- length: 1254
- percent_id: 95.06
- result: reject_bad_break
- row_1: 1020
- row_11: [1295]
- row_13: ['0']
- row_8: C
- src_id: YS2-10a02.q1k
- src_start: 1295
- src_stop: 42
This may give you some ideas on some more meaningful names ('row_8'
looks like an obvious candidate for replacement, for instance).

- If you are using pyparsing 1.4.7, you can abbreviate your calls to
setResultsName to just ("name"), that is, this:
src_id = identifier.setResultsName("src_id")
can be written as just:
src_id = identifier("src_id")

- Don't use the name 'float' for the expression for a real number,
since this masks the builtin Python type float, and more importantly,
the builtin Python conversion function float (which you will want to
use in the parse action for this expression). Perhaps a name like
'real' or 'realNumber' would do.

- There is no need for the trailing space in defining
Literal("ALIGNMENT").

- It is simpler to attach the parse actions to integer and real
themselves, rather than on each line where they are used. If you end
up with some integer field that you don't want converted, you can
define it in situ, like this:
zipCode = Word(nums) # don't use integer for this, don't want it
converted
or define a intString expression that does not do the conversion.

- With these changes, your grammar section becomes a little more
readable:
make_int = lambda t: int(t[0])
make_float = lambda t: float(t[0])
integer = Word( nums ).setParseAction(make_int)
real = Word( nums+".").setParseAction(make_float)
identifier = Word( alphanums+"-_." )

alignment = Literal("ALIGNMENT").suppress()
row_1 = integer("row_1")
src_id = identifier("src_id")
dest_id = identifier("dest_id")
src_start = integer("src_start")
src_stop = integer("src_stop")
dest_start = integer("dest_start")
dest_stop = integer("dest_stop")
row_8 = oneOf("F C")("row_8")
length = integer("length")
percent_id = real("percent_id")
row_11 = (integer +
Optional(Literal("|") +
delimitedList(Word(nums))("subItems"))
)("row_11")
result = Word(alphas+"_")("result")
row_13 = commaSeparatedList("row_13")

(although all the ()'s make row_11 a little tough to follow - this
might deserve getting broken up into several lines.) And yes, I know
that PEP8 says not to align '=' signs on successive assignment
statments, but I truly believe it does help readability at times.

-- Paul

Aug 16 '07 #3

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

Similar topics

3
by: Guy Robinson | last post by:
I have the code below which parses an expression string and creates tokens. Can anyone suggest the best of error checking for things like: Valid variable only obj.attribute -whitespace allowed...
10
by: Angelo Secchi | last post by:
Hi, I have string of numbers and words like ',,,,,,23,,,asd,,,,,"name,surname",,,,,,,\n' and I would like to split (I'm using string.split()) it using comma as separator but I do not want to...
15
by: could ildg | last post by:
In re, the punctuation "^" can exclude a single character, but I want to exclude a whole word now. for example I have a string "hi, how are you. hello", I want to extract all the part before the...
3
by: rh0dium | last post by:
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...
1
by: David Hirschfield | last post by:
Anyone out there use simpleparse? If so, I have a problem that I can't seem to solve...I need to be able to parse this line: """Cen2 = Cen(OUT, "Cep", "ies", wh, 544, (wh/ht));""" with this...
13
by: 7stud | last post by:
To the developer: 1) I went to the pyparsing wiki to download the pyparsing module and try it 2) At the wiki, there was no index entry in the table of contents for Downloads. After searching...
1
by: napolpie | last post by:
----Messaggio originale---- Da: napolpie@tin.it Data: 3-mag-2007 10.02 A: <python-list@python.org> Ogg: problem with meteo datas Hello, I'm Peter and I'm new in python codying and I'm using...
1
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...
3
by: John Carlyle-Clarke | last post by:
Hi. I'm new to Python and trying to use it to solve a specific problem. I have an XML file in which I need to locate a specific text node and replace the contents with some other text. The...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...

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.