繁体   English   中英

打印匹配值的行号

[英]Print line numbers of matching values

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

我看过一些类似的文章,例如; 搜索文件并找到确切的匹配和打印行? 但是我无法成功地应用示例。

我的代码是:

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])

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

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.
print [(i,line) for i,line in enumerate(open(filename),1) if "Assertion" in line]

我可以使用枚举建立您的assertmatch 该代码将类似于以下内容:

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

无需更改其余代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM