2

以下が ctf_output.txt のデータであると仮定します。ロッド番号、表面温度、および中心線温度からタイトルの見出しを抽出し、各ロッドの最高温度のみを抽出したいと考えています。繰り返しなしで、各列に特定の大幅に高い温度を入れていることに注意してください。

Rod 1  
Surface Temperature Centerline Temperature  
500         510    
501         511  
502         512  
503         513  
504         525  
505         515  
535         516  
507         517  
508         518  
509         519  
510         520  
Rod 2  
Surface Temperature   Centerline Temperature  
500               510  
501           511  
502           512  
503           513  
504           555  
505           515  
540           516  
507               517  
508           518  
509           519  
510           520  
Rod 3
Surface Temperature   Centerline Temperature  
500           510  
501           511  
502           512  
503           513  
567           514  
505           515  
506           559  
507           517  
508           518  
509           519  
510           520  

Pythonでこれを行うにはどうすればよいですか? データを取得し、新しい出力ファイルに次の形式で入力する Python スクリプトが必要です。

Rod 1  
Surface Temperature Centerline Temperature  
535         525  

Rod 2  
Surface Temperature   Centerline Temperature  
540           555  

Rod 3  
Surface Temperature   Centerline Temperature  
567           559  
4

1 に答える 1

3

ファイルを 1 行ずつ読み取り、最大値を追跡し、次のセクションが始まるときにそれらを出力します。

with open('ctf_output.txt', 'r') as temps, open(outputfilename, 'w') as output:
    surface_max = centerline_max = None
    for line in temps:
        if line.startswith('Rod'):
            # start of new section
            if surface_max is not None or centerline_max is not None:
                # write maximum for previous section
                output.write('{}\t\t\t{}\n\n'.format(surface_max, centerline_max))
            # write out this line and the next to the output file
            output.write(line)
            output.write(next(temps, ''))
            # reset maxima
            surface_max = centerline_max = 0
        elif line.strip():
            # temperature line; read temperatures and track maxima
            surface, centerline = [int(t) for t in line.split()]
            if surface > surface_max:
                surface_max = surface
            if centerline > centerline_max:
                centerline_max = centerline
    if surface_max or centerline_max:
        # write out last maxima
        output.write('{}\t\t\t{}\n'.format(surface_max, centerline_max))

出力は、入力と同様に 3 つのタブを使用します。

入力例では、次のように記述します。

Rod 1  
Surface Temperature Centerline Temperature  
535         525

Rod 2  
Surface Temperature   Centerline Temperature  
540         555

Rod 3
Surface Temperature   Centerline Temperature  
567         559
于 2013-04-10T18:54:51.457 に答える