【问题标题】:Optimizing python input loop优化python输入循环
【发布时间】:2014-06-07 08:25:39
【问题描述】:

所以我正在构建一个日志解析器,它使用正则表达式,并解析来自标准输入的数据。我希望第一行(如果你愿意的话,是头部)通过我的日志检测器算法,该算法从各种模式测试 regex.search(es),但我不想对每一个输入行都这样做。

我可以做典型的逻辑如:

        First = True
        for inputLine in file:
            if First:
                if testLogType1(inputLine):
                    print "appears to be log 1"
                elif testLogType2(inputLine):
                    print "appears to be log 2"
                First = False
            else:
               pass

必须有一种更简洁、更 Pythonic 的方式来做到这一点?我对编程并不陌生,但我是 Python 新手(初学者)。我可以用 Java 和 C++ 的旧方式来解决问题,但我正在努力变得更好。关于如何改善这一点的任何想法?

"For" loop first iteration 是解决此问题的一种可能方式。也许我的问题是如何使该答案适应标准输入的一次性阅读?

【问题讨论】:

    标签: python


    【解决方案1】:

    例如

    firstline = next(infile)
    if testLogType1(firstline):
        print "appears to be log 1"
    # etc.
    
    for inputLine in infile:
        # process the rest of the lines
    

    【讨论】:

      【解决方案2】:

      只需阅读第一行并检查它是哪种日志类型

      with file as f:
         input = f.readline()
         if testLogType1(inputLine):
             print "appears to be log 1"
         elif testLogType2(inputLine):
             print "appears to be log 2"
      

      【讨论】:

        猜你喜欢
        • 2013-07-17
        • 1970-01-01
        • 2020-11-07
        • 1970-01-01
        • 1970-01-01
        • 2015-04-15
        • 2017-03-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多