我发布了一个关于How to interate over N lines of a text file in Python的问题,但我想让该程序更适用于N行(例如,而不是必须一次收集两行采取四个或六个线路在同一时间在循环中遍历N行,然后转到下一个循环
我希望把这个disp.txt:
116 C 0.12 -0.91 0.39 -0.40 0.31 0.85 -0.66 -0.18 -0.22
117 O 0.00 -0.02 0.00 -0.05 0.05 0.12 -0.57 -0.26 -0.29
116 C -0.03 -0.04 0.00 0.01 0.09 0.19 -0.71 -0.21 -0.26
117 O -0.14 0.88 -0.45 0.47 -0.33 -0.79 0.57 0.16 0.19
要这样:
vibration 1
0.12 -0.91 0.39
0.0 -0.02 0.0
vibration 2
-0.4 0.31 0.85
-0.05 0.05 0.12
vibration 3
-0.66 -0.18 -0.22
-0.57 -0.26 -0.29
vibration 4
-0.03 -0.04 0.00
-0.14 0.88 -0.45
vibration 5 ...
下面是我到目前为止
vibration = 1
with open('disp1.txt','r') as f, open('disp2.txt', 'w') as out:
while True:
next_lines = list(islice(f,2))
m = next_lines
for i in m:
s = i.strip().split('\n')
for j in s:
p = j.split()
v = len(p)
for u in range(2,5,3):
out.write('vibration {}\n'.format(vibration))
out.write(' '.join(p[u:u+3])+'\n')
vibration += 1
for x in range(5,8,3):
out.write(' '.join(p[x:x+3])+'\n')
for y in range(8,11,3):
out.write(' '.join(p[y:y+3])+'\n')
if not next_lines:
break
该图是这样的:
vibration 1
0.12 -0.91 0.39
-0.40 0.31 0.85
-0.66 -0.18 -0.22
vibration 2
0.00 -0.02 0.00
-0.05 0.05 0.12
-0.57 -0.26 -0.29
vibration 3
-0.03 -0.04 0.00
0.01 0.09 0.19
-0.71 -0.21 -0.26
vibration 4
-0.14 0.88 -0.45
0.47 -0.33 -0.79
0.57 0.16 0.19
所以它的阅读在整个页面,而不是阅读数前三列的前两行,然后继续下一组的三个等等。 通过使用isplice它一次读两行,但由于我不明白这两个行都不通过第一个循环(对于范围(2,5,3):)中的u(在范围内(2,5,3):),对于范围内的x(5,8,3):) 取而代之的是将每条线贯穿每个循环。 任何人都可以帮助我吗?
谢谢。
但0.12 -0.91 0.39 -0.40 0.31 0.85 -0.66 - 0.18 -0.22是一行! –
另外,请使用下面的代码:http://www.pythontutor.com/visualize.html#mode=edit –
我的答案是否有效?如果是这样,请将其标为正确(绿色检查)。 –