Newbie Question : "grep"

Larry Bates lbates at websafe.com
Mon Mar 12 17:25:00 CET 2007


moogyd at yahoo.co.uk wrote:
> Hello,
> 
> I am attempting to write my first Python script to extract some
> information from a file, and place it into another file.
> (I am trying to find the physical postions of 4 cells within an FPGA)
> I have a working solution, and would appreciate any comments.
> 
> for line in lines:
> 
>     if "placed" in line:
>         if "i_a/i_b/ROM/" in line:
>             pos = (line.split()[4]).split("_")[1]
>             if "B18" in line:
>                print "        i_a/i_b/ROM/B18 [7:6] LOC =", pos
>             elif "B14" in line:
>                print "        i_a/i_b/ROM/B14 [5:4] LOC =", pos
>             elif "B10" in line:
>                print "        i_a/i_b/ROM/B10 [3:2] LOC =", pos
>             elif "B6" in line:
>                print "        i_a/i_b/ROM/B6 [1:0] LOC =", pos
>             else:
>                print "Error"
> 
> Specific questions
> - Use for "Phrase" in line or line.find("Phrase") >= 0 ?
> - If I increase number of elements I am searching for, then I have
> more elif...elif. Is there a cleaner solution?
> 
> Thanks for any feedback.
> 
> Steven
> 
Something like (not tested):

def search(search_gates, line):
    for gate, index in search_gates:
        pos = (line.split()[4]).split("_")[1]
        if gate in line:
            return "        i_a/i_b/ROM/%s %s LOC =%s" % (gate, index, pos)


    return "Error"


search_gates=[('B6', '[1:0]'), 'B10', '[3:2]'),
               'B14', '[5:4]'), 'B17', '[7:6]')]

for line in lines:
    print search(search_gates, line)

-Larry



More information about the Python-list mailing list