I need to extract (a lot of) info from different text files.
I wonder if there is a shorter and more efficient way than the following:
First part: (N lines long)
N1 = re.compile(r'')
N2 = re.compile(r'')
Nn = re.compile(r'')
with open(filename) as f:
for line in f:
var1 = N1.match(line).group(x).strip()
var2 = N1.match(line).group(x).strip()
varn = Nn
As mentionned in
re module documentation, the regexes you pass through
re methods are cached: depending on the number of expressions you have, caching them yourself might not be useful.
That being said, you should make a list of your regexes, so that a simple for loop would allow you to test all your patterns.
regexes = map(re.compile, ['', '', '', '', ...]) vars = ['']*len(regexes) with open(filename) as f: for line in f: for i,regex in enumerate(regexes): if regex.match(line): var[i] = regex.match(line).group(x).strip()