Recognize loop for from other python scripts

Asked

Viewed 50 times

2

I’m trying to write a python script that can recognize any boucle for in other python scripts.

import re

with open('boite_a_fonctions_v3_1.py', 'r') as f:
    text=f.read()
    a = text.split(" ")
    #print (a)

    boucle = re.compile(r'for"(.*):\t(.*)"')

    def recherche_boucle(a):
        c = []
        for linha in a:
            c += boucle.findall(linha)
        print (c)

    #recherche_boucle (a)

I have nothing as a result (which already makes me happy, at least there are no mistakes!!). Someone has some suggestion?

Ah, a part of the code 'boite_a_fonctions_v3_1.py':

fidr.seek(0)
reg = compile(fmt.get_motif())
id = 0
for line in fidr :
# par ligne
    for seg in reg.findall(line) :
    # par token
        if id == tokenId :
            mot, etq = seg
            return mot, etq
        else :
            id += 1
return None

def get_tokens(fid, fmt, tokenIds):
    if isinstance(tokenIds, int):
        try :
            return get_token(fid,fmt, tokenIds)
        except :
return None
else:
    n = None
    for id in tokenIds:
        try:
            n = len(get_token(fid,fmt, id))
            break
        except:
            pass
    if not n :
        return None

    ret = list()
    for i in range(n) :
        tmp = list()
        for id in tokenIds :
            try:
                tmp.append(get_token(fid,fmt,id)[i])
            except:
                pass
        ret.append(tmp)
    return ret

1 answer

1


In my opinion it is not good to declare a function inside an open file, (works but I think it is not good practice).

You can do it like this:

import re

def recherche_boucle():
    boucle = re.compile('^\s*for (.*?):')
    with open('boite_a_fonctions_v3_1.py', 'r') as f:
        for line_num, line in enumerate(f, 1):
            match = boucle.match(line)
            if match:
                yield (line_num, match.group(1))

for line_num, boucle in recherche_boucle():
    print('descoberto ciclo for na linha {}: {}'.format(line_num, boucle))

If you want the line from for found entirely and not only what is between for and :, you can trade ...group(1) for ...group(0), or if you want the whole line (in this case it will be the same as ...group(0)) you can trade yield (line_num, match.group(1)) for yield (line_num, line)

This function returns a generator, that is to have a list of the results you can list(recherche_boucle())

Solution without regex:

def recherche_boucle():
    with open('boite_a_fonctions_v3_1.py', 'r') as f:
        for line_num, line in enumerate(f, 1):
            if all(match in line for match in ('for ', ':')): # se na linha existe for e :
                yield (line_num, line.strip()) # strip para tirar as quebras de linha

for line_num, boucle in recherche_boucle():
    print('descoberto ciclo for na linha {}: {}'.format(line_num, boucle))
  • Miguel, thank you! Brilliant, I hope one day to have 1% of your talent in python :)

  • 1

    Hehe @pitanga, as in any language practice makes the master, and in the case of python is relatively simple. Training/playing with code is important

Browser other questions tagged

You are not signed in. Login or sign up in order to post.