Need help refactoring my python script

I have a python script that processes a file line by line, if a line matches a regular expression, it calls a function to process it.

My question is: is it better to write refactoring for my script. The script works, but as it is, I need to leave an indent to the right of how I add more and more regular expressions for my file.

Thanks for any idea. Now my code ends as follows:

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)
+3
source share
3 answers

I would switch to using regular expressions data structures for functions. Sort of:

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

Then you just look at them:

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

If you want the matches to be performed in a specific order, you will need to use a list instead of a dictionary, but the principle is the same.

+12

:

handlers = { reg1 : handleReg1, ... }

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

, , , : . break , , . , , :

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

for line in fi.readlines():
    for reg, handler in handlers:
        x = reg.match(line)
        if x:
            handler(x)
            break
+1

, , - m.group() . , , .

>>> reg = re.compile('(cat)|(dog)|(apple)')
>>> m = reg.search('we like dogs')
>>> print m.group()
dog
>>> print m.groups()
(None, 'dog', None)

, , , .

0

Source: https://habr.com/ru/post/1714805/


All Articles