【发布时间】:2013-01-28 05:50:06
【问题描述】:
我想创建一个 python 脚本来比较一个工具生成的两个日志文件(名为 foo.log 和 bar.log)。
日志文件有一些可以忽略的行和一些不能忽略的行(用于比较)。
我创建了正则表达式来识别可以忽略的行。 以下是我实现代码的方式:
import re
p_1 = re.compile(...) # Pattern 1 to be ignored
p_2 = re.compile(...) # Pattern 2 to be ignored
p_3 = re.compile(...) # Pattern 3 to be ignored
...
p_n = re.compile(...) # Pattern n to be ignored
with open("foo.log", mode = 'r') as foo:
with open("foo_temp.log", mode = 'w') as foo_temp:
for foo_lines in foo:
if p_1.match(foo_lines):
continue
elif p_2.match(foo_lines):
continue
elif p_3.match(foo_lines):
continue
...
...
...
elif p_n.match(foo_lines):
continue
else:
foo_temp.write(foo_lines)
with open("bar.log", mode = 'r') as bar:
with open("bar_temp.log", mode = 'w') as bar_temp:
for bar_lines in bar:
if p_1.match(bar_lines):
continue
elif p_2.match(bar_lines):
continue
elif p_3.match(bar_lines):
continue
...
...
...
elif p_n.match(bar_lines):
continue
else:
bar_temp.write(bar_lines)
运行脚本后,我会得到两个文件 foo_temp.log 和 bar_temp.log,稍后我会使用 WinMerge 手动比较它们。
以下是我的问题:
1)有什么方法可以优化我使用正则表达式的方式(我实际上是正则表达式的新手,我觉得在这方面有很多可以优化的地方)
2) 稍后当我必须添加要忽略的新模式时,我能否从用户的角度更轻松地添加新模式。 (目前我需要添加一个新模式,然后在 2 个位置进行检查——一个用于foo.log,一个用于bar.log)
3) 我听说在处理巨大的文件时使用了生成器。虽然我比较的日志相对较小(最大 50MB),但我是否应该研究如何使用生成器并将它们合并到我的脚本中?
4) 与其创建foo_temp.log 和bar_temp.log 并使用WinMerge 进行手动检查,有没有一种方法可以在Python 本身中进行(减少的文件的)比较?可能来自filecmp 模块?
注意:一些可以忽略的行在两个日志中出现混乱(乱序):例如在foo.log 中可能是以下模式:
Line 1: <<Pattern_1: Ignore>>
Line 2: <<Pattern_2: Do not Ignore>>
Line 3: <<Pattern_3: Do not Ignore>>
Line 4: <<Pattern_4: Do not Ignore>>
Line 5: <<Pattern_5: Ignore>>
而bar.log 可能具有以下模式:
Line 1: <<Pattern_1: Ignore>>
Line 2: <<Pattern_5: Ignore>>
Line 3: <<Pattern_2: Do not Ignore>>
Line 4: <<Pattern_3: Do not Ignore>>
Line 5: <<Pattern_4: Do not Ignore>>
请注意,一旦我们删除了可以忽略的行,这两个文件将具有相同的模式。出于这个原因,我决定一次性删除所有可以忽略的行,然后对缩小的文件进行比较。
【问题讨论】:
标签: regex python-3.x compare