【问题标题】:Print line numbers of matching values打印匹配值的行号
【发布时间】:2014-07-24 16:00:42
【问题描述】:

我有一个 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])

【问题讨论】:

    标签: python


    【解决方案1】:

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

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

    其余代码无需更改。

    【讨论】:

      【解决方案2】:
      print [(i,line) for i,line in enumerate(open(filename),1) if "Assertion" in line]
      

      【讨论】:

        【解决方案3】:

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

        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.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-06-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-02-17
          • 1970-01-01
          相关资源
          最近更新 更多