Corresponder regex multilinha no objeto de arquivo
Como posso extrair os grupos desse regex de um objeto de arquivo (data.txt)?
import numpy as np
import re
import os
ifile = open("data.txt",'r')
# Regex pattern
pattern = re.compile(r"""
^Time:(\d{2}:\d{2}:\d{2}) # Time: 12:34:56 at beginning of line
\r{2} # Two carriage return
\D+ # 1 or more non-digits
storeU=(\d+\.\d+)
\s
uIx=(\d+)
\s
storeI=(-?\d+.\d+)
\s
iIx=(\d+)
\s
avgCI=(-?\d+.\d+)
""", re.VERBOSE | re.MULTILINE)
time = [];
for line in ifile:
match = re.search(pattern, line)
if match:
time.append(match.group(1))
O problema na última parte do código é que eu itero linha por linha, o que obviamente não funciona com regex multilinha. Eu tentei usarpattern.finditer(ifile)
como isso:
for match in pattern.finditer(ifile):
print match
... apenas para ver se funciona, mas o método finditer requer uma string ou buffer.
Eu também tentei esse método, mas não consigo fazê-lo funcionar
matches = [m.groups() for m in pattern.finditer(ifile)]
Qualquer ideia?
Após o comentário de Mike e Tuomas, me disseram para usar .read () .. Algo assim:
ifile = open("data.txt",'r').read()
Isso funciona bem, mas seria a maneira correta de pesquisar no arquivo? Não consigo fazê-lo funcionar ...
for i in pattern.finditer(ifile):
match = re.search(pattern, i)
if match:
time.append(match.group(1))
Solução# Open file as file object and read to string
ifile = open("data.txt",'r')
# Read file object to string
text = ifile.read()
# Close file object
ifile.close()
# Regex pattern
pattern_meas = re.compile(r"""
^Time:(\d{2}:\d{2}:\d{2}) # Time: 12:34:56 at beginning of line
\n{2} # Two newlines
\D+ # 1 or more non-digits
storeU=(\d+\.\d+) # Decimal-number
\s
uIx=(\d+) # Fetch uIx-variable
\s
storeI=(-?\d+.\d+) # Fetch storeI-variable
\s
iIx=(\d+) # Fetch iIx-variable
\s
avgCI=(-?\d+.\d+) # Fetch avgCI-variable
""", re.VERBOSE | re.MULTILINE)
file_times = open("output_times.txt","w")
for match in pattern_meas.finditer(text):
output = "%s,\t%s,\t\t%s,\t%s,\t\t%s,\t%s\n" % (match.group(1), match.group(2), match.group(3), match.group(4), match.group(5), match.group(6))
file_times.write(output)
file_times.close()
Talvez ele possa ser escrito de forma mais compacta e pitônica ....