打印匹配值的行号

时间:2014-07-24 16:00:43

标签: python

我有一个python脚本,我用它来解析日志文件并打印出匹配错误等。我想要做的还是打印找到匹配条目的行号

我看过一些类似的帖子,比如; Search File And Find Exact Match And Print Line? 但我还没能成功应用这些例子。

我的代码是:

from sys import argv

script, filename = argv

with open(filename) as f:
        data = f.read().splitlines()
        # Process counts and matches of events:
        assertmatch = [s for s in data if "Assertion" in s]
        assertcount = len(assertmatch)

if assertcount > 0:
    print " "
    print "ASSERTIONS:"
    print '\n'.join([str(myelement) for myelement in assertmatch])

3 个答案:

答案 0 :(得分:0)

您可以将每行读入字典,其中键是行号,然后在每个字典项上运行匹配算法。如果匹配,请打印密钥。

content = {}

with open(filename) as f:
    lineNum = 0
    for line in f:
        content[lineNum] = line
        lineNum = lineNum + 1

# Do search for each in content, if match, print line key.

答案 1 :(得分:0)

print [(i,line) for i,line in enumerate(open(filename),1) if "Assertion" in line]

答案 2 :(得分:0)

我可以使用枚举构建您的assertmatch。代码如下所示:

assertmatch = []
for i, s in enumerate(data, 1):
    if "Assertion" in s:
        assertmatch.append('Line %05d: %s' % (i, s,))

无需更改剩余代码。