473,396 Members | 2,129 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,396 software developers and data experts.

Pyparsing: Non-greedy matching?

I'm trying to use pyparsing write a screenscraper. I've got some
arbitrary HTML text I define as opener & closer. In between is the HTML
data I want to extract. However, the data may contain the same
characters as used in the closer (but not the exact same text,
obviously). I'd like to get the *minimal* amount of data between these.

Here's an example (whitespace may differ):

from pyparsing import *

test=r"""<tr class="tableTopSpace"><td></td></tr>
<tr class="tableTitleDark"><td class="tableTitleDark">Job
Information</td></tr><tr><td><table width="100%" border="0"
cellspacing="3"><tr>
<td width="110" valign="top"><div align="right"><strong>Job Title:
</strong></div></td>
<td class="ccDisplayCell">Big Old <B
STYLE="background-color:#FFEF95">Head Honcho</B> Boss Man</td></tr>
<tr>
<td width="110" valign="top"><div align="right"><strong>Employer:
</strong></div></td>
<td width="200" nowrap class="ccDisplayCell"><table><tr><td colspan="2"
valign="top">Global Megacorp</td></tr></table></td><td>
<script>
function escapecomp(){
}
"""

data=Combine(OneOrMore(Word(printables)), adjacent=False,
joinString=" ")

title_open=Literal(r"""<td width="110" valign="top"><div
align="right"><strong>Job Title: </strong></div></td>
<td class="ccDisplayCell">""")
title_open.suppress()

title_close=Literal(r"""</td>""")
title_close.suppress()

title=title_open + data + title_close
title2=title_open + (data | title_close)
title.scanString(test).next() Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration
title2.scanString(test).next() ((['<td width="110" valign="top"><div align="right"><strong>Job Title:\n
</strong></div></td>\n<td class="ccDisplayCell">', 'Big Old <B
STYLE="background-color:#FFEF95">Head Honcho</B> Boss Man</td> </tr>
<tr> <td width="110" valign="top"><div align="right"><strong>Employer:
</strong></div></td> <td width="200" nowrap
class="ccDisplayCell"><table><tr><td colspan="2" valign="top">Global
Megacorp</td></tr></table></td> <td> <script> function escapecomp(){
}'], {}), 182, 656)


I'd expected title to work, but it doesn't match at all. ;( In other
test variants, title2 gives extra stuff at the end though not
necessarily to the end of the string (due to unprintable characters,
perhaps).

I want a ParseResult more like:
['<td width="110" valign="top"><div align="right"><strong>Job Title:\n
</strong></div></td>\n<td class="ccDisplayCell">', 'Big Old <B
STYLE="background-color:#FFEF95">Head Honcho</B> Boss Man, '</td>']

I sort of understand why title2 works as it does (the OneOrMore just
slurps up everything), but for the life of me I can't figure out how to
fix it. ;) Is there a way of writing something similar to RE's ".*?" ?

--Pete

--
Peter Fein pf***@pobox.com 773-575-0694

Basically, if you're not a utopianist, you're a schmuck. -J. Feldman
Jul 18 '05 #1
2 2552
"Peter Fein" <pf***@pobox.com> wrote in message
news:ma**************************************@pyth on.org...
I'm trying to use pyparsing write a screenscraper. I've got some
arbitrary HTML text I define as opener & closer. In between is the HTML
data I want to extract. However, the data may contain the same
characters as used in the closer (but not the exact same text,
obviously). I'd like to get the *minimal* amount of data between these.

Here's an example (whitespace may differ):

from pyparsing import *

test=r"""<tr class="tableTopSpace"><td></td></tr>
<tr class="tableTitleDark"><td class="tableTitleDark">Job
Information</td></tr><tr><td><table width="100%" border="0"
cellspacing="3"><tr>
<td width="110" valign="top"><div align="right"><strong>Job Title:
</strong></div></td>
<td class="ccDisplayCell">Big Old <B
STYLE="background-color:#FFEF95">Head Honcho</B> Boss Man</td></tr>
<tr>
<td width="110" valign="top"><div align="right"><strong>Employer:
</strong></div></td>
<td width="200" nowrap class="ccDisplayCell"><table><tr><td colspan="2"
valign="top">Global Megacorp</td></tr></table></td><td>
<script>
function escapecomp(){
}
"""

data=Combine(OneOrMore(Word(printables)), adjacent=False,
joinString=" ")

title_open=Literal(r"""<td width="110" valign="top"><div
align="right"><strong>Job Title: </strong></div></td>
<td class="ccDisplayCell">""")
title_open.suppress()

title_close=Literal(r"""</td>""")
title_close.suppress()

title=title_open + data + title_close
title2=title_open + (data | title_close)
title.scanString(test).next() Traceback (most recent call last):
File "<stdin>", line 1, in ?
StopIteration
title2.scanString(test).next() ((['<td width="110" valign="top"><div align="right"><strong>Job Title:\n
</strong></div></td>\n<td class="ccDisplayCell">', 'Big Old <B
STYLE="background-color:#FFEF95">Head Honcho</B> Boss Man</td> </tr>
<tr> <td width="110" valign="top"><div align="right"><strong>Employer:
</strong></div></td> <td width="200" nowrap
class="ccDisplayCell"><table><tr><td colspan="2" valign="top">Global
Megacorp</td></tr></table></td> <td> <script> function escapecomp(){
}'], {}), 182, 656)


I'd expected title to work, but it doesn't match at all. ;( In other
test variants, title2 gives extra stuff at the end though not
necessarily to the end of the string (due to unprintable characters,
perhaps).

I want a ParseResult more like:
['<td width="110" valign="top"><div align="right"><strong>Job Title:\n
</strong></div></td>\n<td class="ccDisplayCell">', 'Big Old <B
STYLE="background-color:#FFEF95">Head Honcho</B> Boss Man, '</td>']

I sort of understand why title2 works as it does (the OneOrMore just
slurps up everything), but for the life of me I can't figure out how to
fix it. ;) Is there a way of writing something similar to RE's ".*?" ?

--Pete

--
Peter Fein pf***@pobox.com 773-575-0694

Basically, if you're not a utopianist, you're a schmuck. -J. Feldman


Peter -

Well you are correct, OneOrMore just keeps on slurping as long as it
continues to find matching text. Unlike RE's, it does not look ahead in the
RE to treat the next literal as a terminating expression.

In the examples that come with pyparsing, there is an HTML extractor
(getNTPservers.py) that uses a CharsNotIn("<") expression for the body of an
HTML tag. That works for the given case, but wont work for you - the body
of your tag also includes other HTML tags, such as <B>, so a CharsNotIn
would terminate before the complete body were extracted.

Assuming that your <td> tag wont contain any nested <td> tag, you could
define your data content as "everything up until I find '</td>'". For this
you can use pyparsing's SkipTo element. I think if you define data as:
data = SkipTo("</td>")
then your code should start working better.

There are a couple of other points on your sample code. Note that
suppress() is *not* a mutator, but actually a factory method - in
expr.suppress(), expr is not modified by suppress, but returns a Suppress
object wrapped around an expr. So in place of:
title_close=Literal(r"""</td>""")
title_close.suppress()
you should do
title_close=Literal(r"""</td>""").suppress()
or
title_close=Literal(r"""</td>""")
title_close = title_close.suppress()

-- Paul
Jul 18 '05 #2
On 12/31/04 03:00 AM CST, "Paul McGuire" <pt***@austin.rr._bogus_.com>
sayeth:
Assuming that your <td> tag wont contain any nested <td> tag, you
could define your data content as "everything up until I find
'</td>'". For this you can use pyparsing's SkipTo element. I think
if you define data as:
data = SkipTo("</td>")
then your code should start working better.


Hey! It does! ;) I just worked up (note to googlers- don't do this):
goodchars=printables.replace("<", "")
good_ab="<" + (~Literal(r"""/td>""") + SkipTo(">", include=True))
good_ab.setDebug(True)
simple=Word(goodchars)
complex=Combine(simple | good_ab, adjacent=False, joinString="")
data=Combine(OneOrMore(complex), adjacent=False, joinString=" ")
title4=title_open+data

But that would break for closers with more than one ">". Need to stop
thinking like these are regexps. Thanks - this is a great tool. ;)

--
Peter Fein pf***@pobox.com 773-575-0694

Basically, if you're not a utopianist, you're a schmuck. -J. Feldman
Jul 18 '05 #3

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

Similar topics

5
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....
0
by: could ildg | last post by:
pyparsing is very convenient to use. But I want to find some a py tool to parse non-English strings. Does pyparsing support UNICODE strings? If not, can someone tell me what py tool can do it?...
7
by: Steven Bethard | last post by:
How do I make sure that my entire string was parsed when I call a pyparsing element's parseString method? Here's a dramatically simplified version of my problem: py> import pyparsing as pp py>...
4
by: the.theorist | last post by:
Hey, I'm trying my hand and pyparsing a log file (named l.log): FIRSTLINE PROPERTY1 DATA1 PROPERTY2 DATA2 PROPERTYS LIST ID1 data1 ID2 data2
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...
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: 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...
18
by: Just Another Victim of the Ambient Morality | last post by:
Is pyparsing really a recursive descent parser? I ask this because there are grammars it can't parse that my recursive descent parser would parse, should I have written one. For instance: ...
3
by: hubritic | last post by:
I am trying to parse data that looks like this: IDENTIFIER TIMESTAMP T C RESOURCE_NAME DESCRIPTION 2BFA76F6 1208230607 T S SYSPROC SYSTEM SHUTDOWN BY USER...
5
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
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:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...
0
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...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
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...

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.