Py学习  »  Python

分裂Python中的txt文件行

Stb • 2 年前 • 926 次点击  

我有。txt文件格式为:

x1 x2 x3 y1 y2 y3 z1 z2 z3
x1 x2 x3 y1 y2 y3 z1 z2 z3

例如:

   1.9849207e-01   1.9993099e-01   2.0150793e-01   9.6169322e-02   9.6354487e-02   1.0630896e-01   1.5000000e-02   1.6090730e-02   1.5000000e-02
   1.9993099e-01   2.0261176e-01   2.0150793e-01   9.6354487e-02   1.0536750e-01   1.0630896e-01   1.6090730e-02   1.6090730e-02   1.5000000e-02

我使用了以下剪报:

from itertools import *

with open('path/snip.txt', 'r') as f_input, open('path/snip_output.txt', 'w') as f_output:
    values = []
    for line in f_input:
        values.extend(line.split())

    ivalues = iter(values)

    for triple in iter(lambda: list(islice(ivalues, 3)), []):
        f_output.write(' '.join(triple) + '\n')

得到:

x1 x2 x3
y1 y2 y3
z1 z2 z3
x1 x2 x3
y1 y2 y3
z1 z2 z3

然而,以下是我想要的,但我不知道如何在islice中处理两个步骤:

x1 y1 z1
x2 y2 z2
x3 y3 z3
x1 y1 z1
x2 y2 z2
x3 y3 z3
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/129023
 
926 次点击  
文章 [ 2 ]  |  最新文章 2 年前
SorousH Bakhtiary
Reply   •   1 楼
SorousH Bakhtiary    2 年前

你可以这样做:

n = 3
values = []
with open("log.txt") as f, open("output.txt", 'w') as g:
    for line in f:
        lst = line.rstrip().split()
        for i in zip(*[lst[i:i + n] for i in range(0, len(lst), n)]):
            print(*i, file=g)

内容 output.txt :

1.9849207e-01 9.6169322e-02 1.5000000e-02
1.9993099e-01 9.6354487e-02 1.6090730e-02
2.0150793e-01 1.0630896e-01 1.5000000e-02
1.9993099e-01 9.6354487e-02 1.6090730e-02
2.0261176e-01 1.0536750e-01 1.6090730e-02
2.0150793e-01 1.0630896e-01 1.5000000e-02

您需要将返回的列表从 line.rstrip().split() n 大块。然后 zip 您可以并行地遍历它们。

Tomalak
Reply   •   2 楼
Tomalak    2 年前
with open('path/snip.txt', 'r') as f_input, open('path/snip_output.txt', 'w') as f_output:
    for line in f_input:
        xyz = line.split()
        x, y, z = xyz[0:3], xyz[3:6], xyz[6:9]
        for triple in zip(x, y, z):
            f_output.write(' '.join(triple) + '\n')

1.9849207e-01 9.6169322e-02 1.5000000e-02
1.9993099e-01 9.6354487e-02 1.6090730e-02
2.0150793e-01 1.0630896e-01 1.5000000e-02
1.9993099e-01 9.6354487e-02 1.6090730e-02
2.0261176e-01 1.0536750e-01 1.6090730e-02
2.0150793e-01 1.0630896e-01 1.5000000e-02