Python多个if语句

时间:2015-01-20 02:20:14

标签: python regex if-statement

我正在尝试使用Python的正则表达式从日志文件中获取值,在这个过程中我有几个if语句。抓取值的代码部分如下:

# Opening the log file for reading
with open(logFile, 'r') as logfile_read:
for line in logfile_read:
    line = line.rstrip()

# To extract Time or iteration
    if 'Time' in line:
        iteration_time = re.findall(r'^Time\s+=\s+(.*)', line)

# To extract local, global and cumulative values

    if 'local' in line:
        local_global_cumu = re.search(r'sum\s+local\s+=\s+(.*),\s+global\s+=\s+(.*),\s+cumulative\s+=\s+(.*)', line)
        if local_global_cumu:
            contLocal_0_value = local_global_cumu.group(1)
            contGlobal_0_value = local_global_cumu.group(2)
            contCumulative_0_value = local_global_cumu.group(3)
        for t in iteration_time:
            contLocal.write("%s\t%s\n" %(t, contLocal_0_value))
            contGlobal.write("%s\t%s\n" %(t, contGlobal_0_value))
            contCumulative.write("%s\t%s\n" %(t, contCumulative_0_value))

    # To extract execution and cpu time

    if 'ExecutionTime' in line:
        execution_cpu_time = re.search(r'^ExecutionTime\s+=\s+(.*)\s+s\s+ClockTime\s+=\s+(.*)\s+s', line)
        if execution_cpu_time:
           execution_time_0_value = execution_cpu_time.group(1)
           cpu_time_0_value = execution_cpu_time.group(2)
        for t in iteration_time:
            print t

在第二个if语句中,我可以获得t的值。但是,在随后的if语句中,当我尝试print t时,什么都没有。我不知道我哪里出错了。

1 个答案:

答案 0 :(得分:1)

以下检查是否"时间"是该行中的子字符串,然后尝试在"时间" ...

上找到该行开始的所有匹配项
if 'Time' in line:
    iteration_time = re.findall(r'^Time\s+=\s+(.*)', line)

以下包含单词" Time":

if 'ExecutionTime' in line:
    execution_cpu_time = re.search(r'^ExecutionTime\s+=\s+(.*)\s+s\s+ClockTime\s+=\s+(.*)\s+s', line)

当它试图循环iteration_time时,它将为空,因为前一个if已经运行,并且条件是它开始于"时间"意味着你得到一个匹配的空列表。

让我们假装你只有一行,从" ExecutionTime"开始,让我们来看看......

  • if 'Time' in line为真,因此re.findall会运行并返回开头的行的所有匹配项'时间' ...这将是为空,因为行没有以'时间' 开头 - 所以iteration_time = []
  • if 'ExecutionTime' in line为真, 行以' ExecutionTime'开头,当您执行for t in iteration_time时 - 它不会循环,因为上面已经将它设置为空!
相关问题