如何从文本文件中提取数据并导入到新的输出文件中?

2024-05-20 23:50:44 发布

您现在位置:Python中文网/ 问答频道 /正文

假设以下是ctf中的数据_输出.txt,我想提取标题标题从杆#,表面温度和中心线温度,然后只有最高温度为每根和每根杆。请注意,我在每个列中都设置了特定的、明显更高的temp,没有重复。在

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脚本,它将提取数据并用以下格式填充一个新的输出文件:

^{pr2}$

Tags: 数据txt脚本标题格式温度surfacetemp
1条回答
网友
1楼 · 发布于 2024-05-20 23:50:44

您需要逐行读取文件,然后跟踪最大值,并在下一节开始时输出:

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个选项卡,就像您的输入一样。在

对于您的示例输入,以下内容为:

^{pr2}$

相关问题 更多 >