首页 > 解决方案 > 尝试循环/使其更容易在文本文件中执行许多重复替换

问题描述

我是一个处理这个奇怪的旧程序的学生,它只将文件作为输入并直接输出到终端。

我有一个 python 脚本,它生成这个输入文件,并将输出写入一个文本文件。但是,每次运行时,我都必须自己在 python 脚本中手动更改变量。有五个变量实例,它们都采用常量格式。有没有办法可以循环/排列这个?

我的python脚本:

from subprocess import check_output

#time is in UTC format, ie. IST -5.30 hrs
with open("INPUT", 'w') as f_in:                   #INPUT is the input file
    f_in.write("&INPUT\n")
    f_in.write("WLINF = 0.250\n")               #lower frequency value
    f_in.write("WLSUP = 4.0\n")                 #highest frequency value
    f_in.write("WLINC = 0.5\n")                     #wavelength increment
    f_in.write("IDAY = 289\n")                  #computing for a specific day
    f_in.write("ALAT = 23.0329\n")          #latitude of the location
    f_in.write("ALON = 72.5517\n")          #longitude of the location
    f_in.write("IDATM = 3\n")                   #atmopsheric model 2 - mid latitude summer
    f_in.write("ISALB = 5\n")                         #surface albedo feature
    f_in.write("IAER = 5\n")                          #boundary layer aerosol type selection - 5 - user defined spectral dependance of BLA
    f_in.write("WLBAER = .500,.675,.870,.936,1.02\n") #wavelenght points for IAER
    f_in.write("WBAER = 5*0.9\n")                      #single scattering albedo
    f_in.write("GBAER = 5*0.8\n")                      #assymetric factor used with IAER
    f_in.write("TIME = 3\n")                       #Time in IST format (-5.30hr)
    f_in.write("QBAER = 0.553,0.258,0.344,0.31,0.276\n") #extinction efficiency percentage
    f_in.write("ZOUT = 0.0,15.0\n")                         #TOA defining
    f_in.write("/\n")

check_output('slarrt >> output1.csv',shell=True)  #slarrt is the program, and ouytput.csv is the output file

这个脚本

获取需要输入的这些值,将它们写入输入文件,运行其他程序(从输入文件获取输入),并将输出写入 csv 文件。然后我更改脚本中的值。

变量 ALAT、ALON、QBAER 和 TIME 需要在每次运行时更改,并且值在 Excel 表中。无论如何我可以一口气完成它们吗?到目前为止,我一直在手动编辑每一行。

这是数据的样子

https://imgur.com/a/waiMZ67

标签: python

解决方案


将电子表格导出为 csv 文件;使用csv 阅读器遍历行;使用行值来更新您的变量

假设 csv 具有列标题并且QBAER只是连接的AOT xxxx字段:

import csv, operator
extinction_pct = operator.itemgetter('AOT 500','AOT 675','AOT 870','AOT 936','AOT 1020')

with open('csv_export.csv') as f_csv, open("INPUT", 'w') as f_in:
    reader = csv.DictReader(f_csv)
    for row in reader:
        f_in.write("&INPUT\n")
        f_in.write("WLINF = 0.250\n")               #lower frequency value
        f_in.write("WLSUP = 4.0\n")                 #highest frequency value
        f_in.write("WLINC = 0.5\n")                     #wavelength increment
        f_in.write("IDAY = 289\n")                  #computing for a specific day
        #f_in.write("ALAT = {Lat}\n".format(**row))    # for Python versions less than 3.6
        f_in.write(f"ALAT = {row['Lat']}\n")          #latitude of the location
        #f_in.write("ALON = {Long}\n".format(**row))    # for Python versions less than 3.6
        f_in.write(f"ALON = {row['Long']}\n")          #longitude of the location
        f_in.write("IDATM = 3\n")                   #atmopsheric model 2 - mid latitude summer
        f_in.write("ISALB = 5\n")                         #surface albedo feature
        f_in.write("IAER = 5\n")                          #boundary layer aerosol type selection - 5 - user defined spectral dependance of BLA
        f_in.write("WLBAER = .500,.675,.870,.936,1.02\n") #wavelenght points for IAER
        f_in.write("WBAER = 5*0.9\n")                      #single scattering albedo
        f_in.write("GBAER = 5*0.8\n")                      #assymetric factor used with IAER
        #f_in.write("TIME = {Time]}\n".format(**row))    # for Python versions less than 3.6
        f_in.write(f"TIME = {row['Time']}\n")                       #Time in IST format (-5.30hr)
        #f_in.write("QBAER = {}\n".format(','.join(extinction_pct(row)))    # for Python versions less than 3.6
        f_in.write(f"QBAER = {','.join(extinction_pct(row))}\n") #extinction efficiency percentage
        f_in.write("ZOUT = 0.0,15.0\n")                         #TOA defining
        f_in.write("/\n")

使用需要 Python 版本 3.6+的 f 字符串。从数据中如何导出和字段
的问题尚不清楚。 有些软件包可以直接处理 excel 文件,但过程是一样的。TimeQBAER


如果要为每一行数据创建一个新文件并检查它,请将文件创建移动到读取器循环中。为了使事情更具可读性,我将文本构造放入了一个函数中。

def file_text(row):
    # String concatenation isn't the most efficient but it does preserve the comment annotations
    s = ''
    s += "&INPUT\n"
    s += "WLINF = 0.250\n"                             #lower frequency value
    s += "WLSUP = 4.0\n"                               #highest frequency value
    s += "WLINC = 0.5\n"                               #wavelength increment
    s += "IDAY = 289\n"                                #computing for a specific day
    #s += "ALAT = {Lat}\n".format(**row)               # for Python versions less than 3.6
    s += f"ALAT = {row['Lat']}\n"                      #latitude of the location
    #s += "ALON = {Long}\n".format(**row)              # for Python versions less than 3.6
    s += f"ALON = {row['Long']}\n"                     #longitude of the location
    s += "IDATM = 3\n"                                 #atmopsheric model 2 - mid latitude summer
    s += "ISALB = 5\n"                                 #surface albedo feature
    s += "IAER = 5\n"                                  #boundary layer aerosol type selection - 5 - user defined spectral dependance of BLA
    s += "WLBAER = .500,.675,.870,.936,1.02\n"         #wavelenght points for IAER
    s += "WBAER = 5*0.9\n"                             #single scattering albedo
    s += "GBAER = 5*0.8\n"                             #assymetric factor used with IAER
    #s += "TIME = {Time]}\n".format(**row)             # for Python versions less than 3.6
    s += f"TIME = {row['Time']}\n"                     #Time in IST format (-5.30hr)
    #s += "QBAER = {}\n".format(','.join(extinction_pct(row)))    # for Python versions less than 3.6
    s += f"QBAER = {','.join(extinction_pct(row))}\n"  #extinction efficiency percentage
    s += "ZOUT = 0.0,15.0\n"                           #TOA defining
    s += "/\n"
    return s

with open('csv_export.csv') as f_csv:
    reader = csv.DictReader(f_csv)
    for row in reader:
        with open("INPUT", 'w') as f_in:
            f_in.write(file_text(row))
        check_output('slarrt >> output1.csv',shell=True)  #slarrt is the program, and ouytput.csv is the output file

推荐阅读