簡體   English   中英

使用python 3x,是否有辦法將文件中的行移動到特定列,並使每一行(最后一行除外)長度相等?

[英]Using python 3x, is there a way to shift lines in a file to a specific column and make every line (except the last line) of equal length?

下面的示例是使這個問題更容易理解的最佳方法。

我想將“文件1”更改為“文件2”。

文件1

1  2  3  4  5  6  7  8  9
         4  5  6  7  8  9  
1  2  3  4  5  6  7  8  9

文件2

1  2  3  4  5  6  7  8  9
4  5  6  7  8  9  1  2  3   #Note that 4 was shifted to the first column of the 2nd row
4  5  6  7  8  9            #All numbers after 4 were shifted to complete the middle line

解決此問題的最佳方法是什么?

Python 3x中有什么特殊功能可以解決此問題?

我嘗試在這里搜索此問題,但找不到相關的解決方案。 如果這已經被問到,我深表歉意。

我開始通過從文件中提取感興趣的元素並將其存儲到數組中來解決此問題(例如,將“文件1”中的所有數字存儲到數組中)。但是,我很難進行下一步,即將存儲的號碼打印為“文件2”格式。

這是我到目前為止的內容:

#Extract numbers and store into an array

array = [] 
def extract_numbers(filename,start_pattern,end_pattern):  
    with open(filename, 'r') as f:
        for line in f:
            if start_pattern in line:
                for line in f:
                    numbers_wanted = line.split()
                    for number in numbers_wanted:
                        array.append(number)
                    if end_pattern in line:
                        break
extract_numbers("test.txt", "first_title", "second_title")
with open ("new_file.txt", 'w') as new_file:
    for number in array:
        print(number.format(???????)) #I need help here for this specific code.

歡迎所有建議,請不要局限於我提供的代碼。 謝謝!

[...]使每行(最后一行除外)長度相等嗎?

從您的問題尚不清楚該相等長度應該是多少。 最長的線? 第一行? 固定目標號碼?

知道目標長度后,一種簡單的方法可能是將所有值讀入內存中的列表,然后逐片打印出來。 例如,如果我們可以假設第一行確定目標長度,則這是實現目標長度的一種方法,以獲得與您的問題相同的輸出:

import re

re_splitter = re.compile(r'\s+')

with open('input.txt') as fh:
    values = re_splitter.split(fh.readline().strip())
    target_len = len(values)

    for line in fh:
        values += re_splitter.split(line.strip())

    while values:
        print(' '.join(values[:target_len]))
        values = values[target_len:]

另一種方法,根據需要在內存中僅存儲足夠的數據:

with open('input.txt') as fh:
    values = re_splitter.split(fh.readline().strip())
    target_len = len(values)

    for line in fh:
        if len(values) >= target_len:
            print(' '.join(values[:target_len]))
            values = values[target_len:]

        values += re_splitter.split(line.strip())

    if len(values) >= target_len:
        print(' '.join(values[:target_len]))
        values = values[target_len:]

    print(' '.join(values))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM