我使用Python的正则表达式从典型的科学模拟日志文件中获取少量值。此日志文件的缩短版本如下所示:
Time = 500
smoothSolver: Solving for Ux, Initial residual = 0.000185956, Final residual = 8.56685e-06, No Iterations 4
smoothSolver: Solving for Uy, Initial residual = 0.00338876, Final residual = 0.00016085, No Iterations 4
smoothSolver: Solving for Uz, Initial residual = 0.00412929, Final residual = 0.000195655, No Iterations 4
GAMG: Solving for p, Initial residual = 0.0135009, Final residual = 0.000416508, No Iterations 2
time step continuity errors : sum local = 8.12599e-05, global = -2.7703e-06, cumulative = -0.0058176
smoothSolver: Solving for omega, Initial residual = 6.29185e-05, Final residual = 4.26272e-06, No Iterations 3
smoothSolver: Solving for k, Initial residual = 0.000658395, Final residual = 4.89427e-05, No Iterations 3
ExecutionTime = 537.04 s ClockTime = 537 s
我的代码是:
with open(logFile, 'r') as logfile_read:
for line in logfile_read:
line = line.rstrip()
if 'Time' in line:
iteration_time = re.findall(r'^Time\s+=\s+(.*)', line)
if ('local' or 'global' or 'cumulative') 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)
contLocal_0_time_value = zip(iteration_time,contLocal_0_value)
print contLocal_0_value
print contLocal_0_time_value
我得到的输出是:
8.12599e-05
[('500', '8')]
在zip()
之后,值8.12599e-05
被截断为8
为什么zip()
会发生这种情况以及如何解决这个问题?我无法在float()
中使用zip()
。
答案 0 :(得分:1)
来自zip
&#39的doc:
The returned list is truncated in length to the length of the shortest argument sequence.
您正在使用字符串['500']
压缩列表'8.12599e-05'
,因此结果为[('500', '8')]
。
我不确定你要做什么,但你可能意味着
zip(iteration_time, [contLocal_0_value])
答案 1 :(得分:0)
问题是contLocal_0_value
是字符串而非列表,因此您需要使用zip(iteration_time, [contLocal_0_value])
。
import re
with open(logFile, 'r') as logfile_read:
for line in logfile_read:
line = line.rstrip()
if 'Time' in line:
iteration_time = re.findall(r'^Time\s+=\s+(.*)', line)
if ('local' or 'global' or 'cumulative') in line:
local_global_cumu = re.search(
(r'sum\s+local\s+=\s+(.*),\s+global\s+=\s+(.*),'
r'\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)
contLocal_0_time_value = zip(iteration_time, [contLocal_0_value])
print contLocal_0_value
print contLocal_0_time_value
输出:
8.12599e-05
[('500', '8.12599e-05')]