Recognize loop for other python scripts

2

I am trying to write a python script that can reconher 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 !!). Anyone have any suggestions?

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
    
asked by anonymous 20.02.2017 / 09:31

1 answer

1

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

You can do 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 of for found in whole and not only what is between for and : , you can change ...group(1) by ...group(0) , or if you want the whole line (in this case give ...group(0) ) you can change yield (line_num, match.group(1)) by yield (line_num, line)

This function returns a generator, ie to have a list of 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))
    
20.02.2017 / 10:56