[英]Reading log file in Python
I have a log file with following content. 我有一个包含以下内容的日志文件。 I like to read
Iteration value
and detection_eval
value 我喜欢读取
Iteration value
和detection_eval
值
I0704 18:10:31.097334 2421 solver.cpp:433] Iteration 200, Testing net (#0)
I0704 18:10:31.149454 2421 net.cpp:693] Ignoring source layer mbox_loss
I0704 18:10:40.241916 2421 solver.cpp:546] Test net output #0: detection_eval = 0.00273318
I did 我做了
accuracy_pattern = r"Iteration (?P<iter_num>\d+), Testing net \(#0\)\n.* detection_eval = (?P<accuracy>[+-]?(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)"
But nothing is read, what is the issue? 但是什么也没读,这是什么问题?
EDIT: Then I read accuracy_pattern to array as 编辑:然后我读取precision_pattern数组为
for r in re.findall(accuracy_pattern, log):
iteration = int(r[0])
accuracy = float(r[1]) * 100
log has all file content and read as follow 日志中包含所有文件内容,其内容如下
with open(log_file, 'r') as log_file2:
log = log_file2.read()
As far as I understand your data, the following regex should work: 据我了解您的数据,以下正则表达式应该有效:
pattern = "Iteration\s+(\d+)|detection_eval\s+=\s+(.+$)"
for it,de in re.findall(pattern, log, flags=re.M):
if it:
print('Iteration', int(it))
if de:
print('detection_eval', float(de))
#Iteration 200
#detection_eval 0.00273318
However, reading the whole log file at once is usually a bad idea. 但是,一次读取整个日志文件通常不是一个好主意。 Consider reading one line at a time:
考虑一次读取一行:
with open(log_file, 'r') as log_file2:
for line in log_file2:
for it,de in re.findall(pattern, log):
if it:
print('Iteration', int(it))
if de:
print('detection_eval', float(de))
Using re.search
使用
re.search
Demo: 演示:
import re
with open(log_file, "r") as infile:
for line in infile:
iteration = re.search("Iteration (\d+)", line)
if iteration:
print iteration.group()
detection_eval = re.search("detection_eval = (\d.*)", line)
if detection_eval:
print detection_eval.group()
Output: 输出:
Iteration 200
detection_eval = 0.00273318
Or using re.findall
或使用
re.findall
iteration = re.findall(r"Iteration (\d+)", log )
detection_eval = re.findall(r"detection_eval = (\d.*)", log )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.