1

我有一个数据文件,前 8 行如下所示。(为了清楚这个问题,用字母代替实际值之后)

    a,b,c
    d
    e,f
    g,h
    i,j,k
    l
    m,n
    o,p

这些代表有关电网中变压器的数据。前 4 行是关于变压器 1 的信息,接下来的四行是关于变压器 2 的信息,依此类推。

变量 ap 可以是整数、浮点数或字符串

我需要在 python 中编写一个脚本,以便将一个变压器的数据分布在 4 行上,而不是将其全部放在一行上。

更准确地说,我希望将上述两行转换为

  a,b,c,d,e,f,g,h
  i,j,k,l,m,n,o,p

并将其写入另一个数据文件。
我该怎么做呢?

4

4 回答 4

1

如果总是 4 行(此行中的字段数不重要)是关于一件事的信息,你可以这样:

with open('your_data_file.txt', 'r') as i, open('output_file.txt', 'w') as o:
    new_info = 4
    for line in i:
        o.write(line.strip())  # use .strip() to remove new line character
        new_info -= 1
        if new_info == 0:
            o.write('\n')  # begin info of new transformer in new line
            new_info = 4
        else:
            o.write(',')  # write a , to separate the data fields, but not at
                          # the end of a line

在此代码中,将打开一个输入和一个输出文件,并且始终将 4 行输入中的一行输出“转换”并写入。

于 2013-05-18T15:15:18.503 回答
1

使用来自 itertools 的石斑鱼配方

from itertools import izip_longest
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)


with open('z.t') as f:
    d = grouper(f, 4)
    for x in d:
            print ','.join(y.rstrip() for y in x) 

a,b,c,d,e,f,g,h
i,j,k,l,m,n,o,p
于 2013-05-18T15:27:44.777 回答
0

假设此数据模式在整个输入文件中持续存在...

首先,您需要读取包含数据的文件(filename是一个字符串;文件的路径)

f = open(filename, "r")   # open in read mode
content = f.read()        # read everything as one string
f.close()

一旦您以字符串 ( content) 的形式读取文件的内容,只需收集所有数据,对其进行划分,然后对其进行重组。

假设每个变压器关联8个值;

content = content.replace('\n', ',')   # put everything on one line
values = content.split(',')            # split it all up

lines = []
for i in range(0, len(values), 8):          # iterate by 8 elements
    lines.append(",".join(values[i:i+8]))   # merge these values and add to lines

output = "\n".join(lines)                   # merge these lines (via new lines)

然后,您将继续将输出写入文件;

f = open(newfile, "w")  # open the new file in write mode; it doesn't have to exist yet
f.write(output)
f.close()
于 2013-05-18T15:13:09.807 回答
0

这个怎么样:

import itertools

# From itertools recipes
def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return itertools.izip_longest(fillvalue=fillvalue, *args)

with open('output', 'w+') as fout:
    with open('filename') as fin:
        fout.writelines(','.join(tup) + '\n' for tup in
            grouper(itertools.chain.from_iterable(
                line.strip().split(',') for line in fin), 8, '-'))

这会将所有行中的所有字段链接在一起作为单个可迭代对象,然后将它们分组为 8 个块,然后将它们写入新文件。

这个秘籍并不关心每一行有多少列——它甚至可以在整个文件中改变。它只是将它们作为连续的 8 元组

于 2013-05-18T15:27:58.043 回答