Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need help in refactoring my python script

Tags:

python

I have a python script which process a file line by line, if the line matches a regex, it calls a function to handle it.

My question is is there a better write to refactor my script. The script works, but as it is, i need to keep indent to the right of the editor as I add more and more regex for my file.

Thank you for any idea. Now my code end up like this:

for line in fi.readlines():

       result= reg1.match(line)

       if result:
               handleReg1(result)

       else:
               result = reg2.match(line)

               if result:
                       handleReg2(result)
               else:
                       result = reg3.match(line)

                       if result:
                               handleReg3(result)
                       else:
                               result = reg4.match(line)

                               if result:
                                       handleReg4(result)
                               else:
                                       result = reg5.match(line)

                                       if result:
                                              handleReg5(result)
like image 294
n179911 Avatar asked Aug 04 '26 14:08

n179911


2 Answers

I'd switch to using a data structure mapping regexes to functions. Something like:

map = { reg1: handleReg1, reg2: handleReg2, etc }

Then you just loop through them:

for reg, handler in map.items():
    result = reg.match(line)
    if result:
       handler(result)
       break

If you need the matches to happen in a particular order you'll need to use a list instead of a dictionary, but the principal is the same.

like image 54
samtregar Avatar answered Aug 06 '26 04:08

samtregar


Here's a trivial one:

handlers = { reg1 : handleReg1, ... }

for line in fi.readlines():
    for h in handlers:
        x = h.match(line)
        if x:
            handlers[h](x)

If there could be a line that matches several regexps this code will be different from the code you pasted: it will call several handlers. Adding break won't help, because the regexps will be tried in a different order, so you'll end up calling the wrong one. So if this is the case you should iterate over list:

handlers = [ (reg1, handleReg1), (reg2, handleReg2), ... ]

for line in fi.readlines():
    for reg, handler in handlers:
        x = reg.match(line)
        if x:
            handler(x)
            break
like image 36
ilya n. Avatar answered Aug 06 '26 03:08

ilya n.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!