如何以 Python 方式将三联线排列成列并避免对双联线这样做?

How to pythonically order triplets of line into columns and avoiding doing that for doublets of line?

抱歉,如果我的问题不是很清楚。基本上我想做的是通过连续读取文件 3 个非空行(三元组)来识别,并且对于每个三元组,将它们排序到列中的另一个文件中(如下所述)。一个棘手的部分是仅对三胞胎而不是双胞胎(连续两个非空行)执行此操作。

输入:

line1
line2
line3
(empty line)
(empty line)
line4
line5
(empty line)
line6
line7
line8
(empty line)
(empty line)
line9
line10
(empty line)
line11
line12
line13
output: 
line1 line2 line3 
line6 line7 line8 
line11 line12 line13

您会注意到,doublets 后面可以跟两个空行。 对于我当前的问题,我将不胜感激,因为我是 python 新人,经过几个小时的尝试,我仍然坚持使用我的代码。谢谢:)

我建议您计算一下您目前已阅读的非空行数。 如果你遇到一个空行并且你知道自上一个空行以来你只读了两个非空行,你可以扔掉最后一行。 但是,如果你发现你读取了三个非空行,你将它们写入新文件。

with open('input_file.txt', 'r') as input_file:
    with open('output_file.txt', 'w') as output_file:
        non_empty = 0
        previous_lines = []
        for line in input_file.readlines():
            if line == '\n':
                if non_empty == 3:  # found a triple
                    output_file.write(' '.join(previous_lines) + '\n')
                # if it's not a triple, just ignore it
                # reset the counter so we can detect the next triple
                non_empty = 0
                previous_lines = []
            else:
                # record a non-empty line for later use
                previous_lines.append(line.replace('\n', ''))
                # and important: count how many non-empty lines there are
                non_empty += 1