修改复杂的固定文本文件?

时间:2017-11-29 23:25:43

标签: python

我有一个像这个例子的文本文件:

fit c3 start=1455035 step=1
2.000000
2.000000
2.000000
2.000000
2.000000
2.000000
fit c2 start=5195348 step=1
1.000000
1.000000
1.000000
1.000000
1.000000
fit c4 start=6587009 step=1
10.000000
10.000000
10.000000
10.000000
10.000000

每个文本行(以fit开头)后跟一些数字行。我想总结每个文本行下面的所有数字(因此它们在同一组中)并将该组的最后一个数字替换为该特定组的数量之和,并将其余数字替换为1.000000 - 如这个输出示例:

fit c3 start=1455035 step=1
1.000000
1.000000
1.000000
1.000000
1.000000
12.000000
fit c2 start=5195348 step=1
1.000000
1.000000
1.000000
1.000000
5.000000
fit c4 start=6587009 step=1
1.000000
1.000000
1.000000
1.000000
50.000000

并将其写入新文件。

我在Python中尝试了这段代码,但实际上没有返回我想要的内容。

infile = open("file.txt", "r")
for line in infile:
    if line startswith"fit":
        for l in len(line):
            line[l] = line + line[l+1]

你知道如何在python中做到这一点吗?

2 个答案:

答案 0 :(得分:2)

lines = open("file.txt", "r").read().splitlines()
_sum = 0.
for i, line in enumerate(lines):
  if not line.startswith('fit') :
    _sum += float(line) 
    lines[i] = '{:0.6f}'.format(1.)

  if line.startswith('fit') and  i > 0:
    lines[i-1] = '{:0.6f}'.format(_sum)
    _sum = 0
  elif i+1 >= len(lines):
    lines[i] = '{:0.6f}'.format(_sum)


print '\n'.join(lines)

输出

fit c3 start=1455035 step=1
1.000000
1.000000
1.000000
1.000000
1.000000
12.000000
fit c2 start=5195348 step=1
1.000000
1.000000
1.000000
1.000000
5.000000
fit c4 start=6587009 step=1
1.000000
1.000000
1.000000
1.000000
50.000000

答案 1 :(得分:0)

请试一试。

prev_string = ' '
global_string = ''
temp_sum = 0

with open('file.txt', 'r') as f:
    prev_string = f.readline()
    for line in f:
        if prev_string[0] == 'f':
            global_string += prev_string
        elif (line[0].isdigit() and prev_string[0].isdigit()):
            global_string += '1.000000\n'
            temp_sum += float(prev_string[:-1])
        else:
            temp_sum += float(prev_string[:-1])
            global_string += str(format(temp_sum, '.6f')) + '\n'
            temp_sum = 0
        prev_string = line
    global_string += str(format(temp_sum + float(prev_string[:-1]), '.6f'))

with open('output.txt', 'w') as out:
    out.write(global_string)