Newbie Question : "grep"
nobody at invalid.com
Mon Mar 12 17:56:30 CET 2007
<moogyd at yahoo.co.uk> wrote in message
news:1173714587.830723.59210 at 8g2000cwh.googlegroups.com...
> - If I increase number of elements I am searching for, then I have
> more elif...elif. Is there a cleaner solution?
I'm not sure exactly what your lines look like, but this script implies that
every line that matches 'i_a/i_b/ROM' is one of the known list you are
looking for. Maybe that's exactly right...
Below is some code that I think is an incremental improvement over writing
lots of alternative if-statements.
I beleive it has the same behaviour, though it is totally untested:
tags = [
['B18', (7, 6)],
['B14', (5, 4)],
['B10', (3, 2)],
['B6', (1, 0)],
for line in lines:
if "placed" in line:
if "i_a/i_b/ROM/" in line:
pos = (line.split()).split("_")
found = False
for (tag, (start, end)) in tags:
if tag in line:
found = True
print " i_a/i_b/ROM/%s [%i:%i] LOC =" %\
(pos, tag, start, end)
This way, you just need to maintain your data structure (tags), instead
of writing lots of repettitive code.
If there is a definite pattern to the part that looks like a slice (what I
am calling (start, end)), then you could
programmatically generate that as well, of course.
The list of things you are looking for could be in a separate file, etc.
The sensible thing to do sort of depends on how big this list of stuff you
are looking for is going to grow and how much you are going to use this
program. Do what makes sense for you.
You may want to explore the 're' module as well (regular expressions)
http://docs.python.org/modindex.html , which may or may not improve
performance, readability, maintainability, etc.
See also section 10.10 of the Python Tutorial if you are interested in code
performance issues: http://docs.python.org/tut/tut.html
Hope that helps,
More information about the Python-list