簡體   English   中英

如何使用python將txt文件中的文本復制並重新排列到另一個文件?

[英]How can I copy and rearrange text from a txt file to another with python?

我正在嘗試使用 python 將一些文本從一個文本文件復制和編輯到另一個文本文件。 我一直在環顧四周,找到了一些簡單的例子,但仍然找不到我需要的一切。

我的原文是這樣的(從一些文本開始,然后有一個以 NODE 開頭的標題行,然后是一個以----開頭的行,然后是我感興趣的數據):

[The file starts with a lot of text, which I have not includeded here ...]
 NODE DISPLACEMENT AND ROTATIONS DEFAULT PRINTOUT                      Unit System : kN , m

__________________________________________________


 NODE       LC               UX          UY          UZ          RX    RY          RZ
------ -------- ---- ----------- ----------- ----------- ----------- ----------- -----------

   101      AW2  Max       0.005       0.000       0.001         0.0         0.0         0.0
                 Min      -0.007      -0.000      -0.000        -0.0        -0.0        -0.0

             LL  Max       0.021       0.000       0.002         0.0         0.0         0.0
                 Min      -0.031      -0.000      -0.003        -0.0        -0.0        -0.0

   102      AW2  Max       0.003       0.000       0.000         0.0         0.0         0.0
                 Min      -0.003      -0.000      -0.000        -0.0        -0.0        -0.0

我希望我的程序打印以下內容:

   101,      AW2,  Max,       0.005,       0.000,       0.001,         0.0,         0.0,         0.0
   101,      AW2,  Min,      -0.007,      -0.000,      -0.000,        -0.0,        -0.0,        -0.0
   101,       LL,  Max,       0.021,       0.000,       0.002,         0.0,         0.0,         0.0
   101,       LL,  Min,      -0.031,      -0.000,      -0.003,        -0.0,        -0.0,        -0.0
   102,      AW2,  Max,       0.003,       0.000,       0.000,         0.0,         0.0,         0.0
   102,      AW2,  Min,      -0.003,      -0.000,      -0.000,        -0.0,        -0.0,        -0.0

這是我的嘗試,但它沒有提供所需的輸出。 我不知道如何解決這個問題:

node = 0
with open("infile.txt",'r') as inFile:
    with open("outfile.txt","w") as outFile:
        lines = inFile.read().splitlines()
        for i, line in enumerate(lines):
            if "NODE" in lines[i]:
                node = node + 1
                if node ==2:                   #it is the line "NODE  LC  UX  UY  UZ  RX  RY RZ"
                    j=3                        #it is the line "101 Aw2 Max 0.005 0.000 0.001 (...)"
                    while lines[i+j] != "\n":
                        for word in lines[i+j].split():

                         nodenumber = word[1]
                         loadcase = word[2]
                         MaxMin = word[3]
                        #How can I make it work for everyline? (they don't all have the same structure)

                        outFile.write( ) #How do I create the output that I want with comas?
                        outFile.write("\n")
                        j=j+1

你可以使用 re 來獲得你想要的線條。

import re

lines = [

        ' NODE       LC               UX          UY          UZ          RX    RY          RZ',
        '------ -------- ---- ----------- ----------- ----------- ----------- ----------- -----------',
        '',
        '   101      AW2  Max       0.005       0.000       0.001         0.0         0.0         0.0',
        '                 Min      -0.007      -0.000      -0.000        -0.0        -0.0        -0.0',
        '',
        '             LL  Max       0.021       0.000       0.002         0.0         0.0         0.0',
        '                 Min      -0.031      -0.000      -0.003        -0.0        -0.0        -0.0',
        '',
        '   102      AW2  Max       0.003       0.000       0.000         0.0         0.0         0.0',
        '                 Min      -0.003      -0.000      -0.000        -0.0        -0.0        -0.0',
    ]

for line in lines:
    if re.findall(r'(Max|Min)\s+\-?\d+\.\d+\s+', line):
        print(line)

結果

101      AW2  Max       0.005       0.000       0.001         0.0         0.0         0.0
              Min      -0.007      -0.000      -0.000        -0.0        -0.0        -0.0
          LL  Max       0.021       0.000       0.002         0.0         0.0         0.0
              Min      -0.031      -0.000      -0.003        -0.0        -0.0        -0.0
102      AW2  Max       0.003       0.000       0.000         0.0         0.0         0.0
              Min      -0.003      -0.000      -0.000        -0.0        -0.0        -0.0

使用 split() 您可以將每一行的內容放在一個列表中。 這樣就可以很容易地根據您的意願重新格式化數據。

for line in lines:
    if re.findall(r'(Max|Min)\s+\-?\d+\.\d+\s+', line):
        line_parts = line.split()
        print(line_parts)

結果

['101', 'AW2', 'Max', '0.005', '0.000', '0.001', '0.0', '0.0', '0.0']
['Min', '-0.007', '-0.000', '-0.000', '-0.0', '-0.0', '-0.0']
['LL', 'Max', '0.021', '0.000', '0.002', '0.0', '0.0', '0.0']
['Min', '-0.031', '-0.000', '-0.003', '-0.0', '-0.0', '-0.0']
['102', 'AW2', 'Max', '0.003', '0.000', '0.000', '0.0', '0.0', '0.0']
['Min', '-0.003', '-0.000', '-0.000', '-0.0', '-0.0', '-0.0']

格式化

col_1 = ''
col_2 = ''
for line in lines:
    if re.findall(r'(Max|Min)\s+\-?\d+\.\d+\s+', line):
        line_parts = line.split()
        if len(line_parts) == 9:
            col_1 = line_parts[0]
            col_2 = line_parts[1]
            line_parts.pop(0)
            line_parts.pop(0)
        elif len(line_parts) == 8:
            col_2 = line_parts[0]
            line_parts.pop(0)

        str = '{:>4s}, {:>4s},'.format(col_1, col_2)
        for line_part in line_parts:
            str = str + '{:>8s},'.format(line_part)
        str = str[0:-1]
        print(str)

結果

 101,  AW2,     Max,   0.005,   0.000,   0.001,     0.0,     0.0,     0.0
 101,  AW2,     Min,  -0.007,  -0.000,  -0.000,    -0.0,    -0.0,    -0.0
 101,   LL,     Max,   0.021,   0.000,   0.002,     0.0,     0.0,     0.0
 101,   LL,     Min,  -0.031,  -0.000,  -0.003,    -0.0,    -0.0,    -0.0
 102,  AW2,     Max,   0.003,   0.000,   0.000,     0.0,     0.0,     0.0
 102,  AW2,     Min,  -0.003,  -0.000,  -0.000,    -0.0,    -0.0,    -0.0

最好使用pandas 使用內置方法pandas.read_csv() 讀取數據框中的文本文件

import pandas as pd
df = pd.read_csv('filename.txt', delimiter = '\t', lineterminator ='\n')

您可能需要根據文件類型(如 utf-8 或其他內容)使用更多參數並填充列

df[column_name or number].fillna( method ='ffill', inplace = True)

上面的代碼將糾正上單元格中的任何值

暫無
暫無

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

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