2013-04-10 14 views
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 

回答

3

,然後保持最大值和輸出的跟蹤那些在下次部分開始:

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 
+0

太好了!但是你在第一個output.write中錯過了一個括號(第8行)。 – 2013-04-10 19:09:29

+1

感謝您的提醒;固定。 – 2013-04-10 19:11:57

相關問題