优化python输入循环
所以我正在构建一个日志解析器,它使用正则表达式,并且正在解析来自stdin的数据。我希望第一行(头部,如果你愿意的话)通过我的日志检测器算法,该算法从各种模式测试regex.search,但我不想对每一个输入行都这样做 我可以做典型的逻辑,例如:优化python输入循环,python,Python,所以我正在构建一个日志解析器,它使用正则表达式,并且正在解析来自stdin的数据。我希望第一行(头部,如果你愿意的话)通过我的日志检测器算法,该算法从各种模式测试regex.search,但我不想对每一个输入行都这样做 我可以做典型的逻辑,例如: First = True for inputLine in file: if First: if testLogType1(inputLine):
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
必须有一种更干净、更像蟒蛇的方式来做到这一点?我对编程并不陌生,但我对Python(入门级)是新手。我可以用Java、C++的老方法艰难地完成任务,但我正在努力做得更好。关于如何改进这一点有什么想法吗
这是解决这一问题的一种可能方式。也许我在这里的问题是,我如何使这个答案适应标准输入的一次性阅读 只需阅读第一行并检查它是哪种日志类型
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"
例如
firstline = next(infile)
if testLogType1(firstline):
print "appears to be log 1"
# etc.
for inputLine in infile:
# process the rest of the lines