我有这种(某种)大文本文件,我必须找到告诉当前操作的特定行。对于其中一些线路,我找到了另一条线路(通常在下面4-6线路),它告诉我们所述行动的信息。 我当前的脚本如下所示:
fileLines = file.readlines()
nrlines = enumerate(fileLines)
for i,line in nrlines:
if "TiltArmAxis::StateGoingToAlmostUp" in line:
print "%d - %s" % (i, line)
for i,line in range(i, i+7):
if "Axis::StatePositionMode:" in line:
print "%d - %s" % (i, line)
它适用于第一个但不是第二个,我得到:
4520 - "2014-11-13 08:13:43",T:305310 TiltArmAxis - changing state from TiltArmAxis::StateAtDown -> TiltArmAxis::StateGoingToAlmostUp
但是:
for i,line in range(i, i+7):
TypeError: unpack non-sequence
所以基本上,我想用枚举对每一行进行索引,然后在其中找到带有“TiltArmAxis :: StateGoingToAlmostUp”的行并打印。然后在接下来的6行中查找“Axis :: StatePositionMode:”,如果出现这样的行(如果没有,跳过它);打印它然后转到下一个“TiltArmAxis :: StateGoingToAlmostUp”。
有更有效的方法吗?请帮忙
编辑:删除了args,
range(i, i+7):
仍然得到相同的错误
答案 0 :(得分:1)
我们可以简单地索引行列表。
with open("test.txt", "rt") as f:
lines = f.readlines()
for i in range(len(lines)):
if "TiltArmAxis::StateGoingToAlmostUp" in lines[i]:
print "%d - %s" % (i, lines[i])
for j in range(i, min(i+7, len(lines))):
if "Axis::StatePositionMode:" in lines[j]:
print "%d - %s" % (j, lines[j])
或者,我们仍然可以使用enumerate
:
with open("test.txt", "rt") as f:
lines = f.readlines()
for i, line in enumerate(lines):
if "TiltArmAxis::StateGoingToAlmostUp" in line:
print "%d - %s" % (i, line)
for j, line in enumerate(lines[i:i+7]):
if "Axis::StatePositionMode:" in line:
print "%d - %s" % (i+j, line)
最后一个没有将整个文件加载到RAM的解决方案。它假设字符串" TiltArmAxis :: StateGoingToAlmostUp"在接下来的6行中不再出现。
with open("test.txt", "rt") as f:
look_for_next = False
for i, line in enumerate(f):
if look_for_next:
if i < limit:
if "Axis::StatePositionMode:" in line:
print "%d - %s" % (i, line)
look_for_next = False
else:
look_for_next = False
else:
if "TiltArmAxis::StateGoingToAlmostUp" in line:
print "%d - %s" % (i, line)
look_for_next = True
limit = i + 7
答案 1 :(得分:0)
let foo (f : (string -> 'b[])) (s : string) (t : Attribute) =
let attrs = f s
match attrs.Length with
| 0 -> None
| _ -> t(o = attrs.[0])
是t
和range(i, i+7)
之间的整数的简单序列。你需要的是:
i
顺便说一下,如果在内循环期间到达文件末尾,则应使用i+7
保护nrlines = enumerate(file)
for i,line in nrlines:
if "TiltArmAxis::StateGoingToAlmostUp" in line:
print "%d - %s" % (i, line)
for j in range(7):
i, line = next(nrlines) # use next on the iterator !
if "Axis::StatePositionMode:" in line:
print "%d - %s" % (i, line)
以避免错误。我不能这样做,因为我不知道你想做什么,除了案例: - )