【问题标题】:Pythonic way to extract values from this text file从此文本文件中提取值的 Pythonic 方式
【发布时间】:2011-06-20 15:13:40
【问题描述】:

我有一个来自旧版软件的输出文件,如下所示。我想从中提取值,例如,我可以将一个名为direct_solar_irradiance 的变量设置为648.957,并将target ground pressure 设置为1013.00

到目前为止,我一直在提取单独的行并像下面这样处理它们(针对我想要提取的不同值重复多次):

values = lines[97].split()
self.irradiance_direct, self.irradiance_diffuse, self.irradiance_env = values

However, I have now found that extra lines are added to the middle of the output when certain parameters are selected.这当然意味着第 97 行将不再具有我需要的值。

鉴于在某些情况下可能会在输出中添加额外的行,是否有一种很好的 Pythonic 方法来提取这些值?我想我需要在文件中搜索已知的文本片段,然后提取它们引用的数字,但我能想到的唯一方法是非常笨拙。

所以:

  1. 有没有一种很好的 Pythonic 方法来搜索这些字符串并提取我想要的值?

  2. 如果没有,还有其他方法可以明智地做到这一点吗? (例如,某种我一无所知的很酷的文本文件解析库)。

    ******************************* 6sV version 1.0B ******************************
    *                                                                             *
    *                       geometrical conditions identity                       *
    *                       -------------------------------                       *
    *                       user defined conditions                               *
    *                                                                             *
    *   month: 14 day :   1                                                       *
    *   solar zenith angle:   10.00 deg  solar azimuthal angle:       20.00 deg   *
    *   view zenith angle:    30.00 deg  view azimuthal angle:        40.00 deg   *
    *   scattering angle:    159.14 deg  azimuthal angle difference:  20.00 deg   *
    *                                                                             *
    *                       atmospheric model description                         *
    *                       -----------------------------                         *
    *           atmospheric model identity :                                      *
    *               midlatitude summer  (uh2o=2.93g/cm2,uo3=.319cm-atm)           *
    *           aerosols type identity :                                          *
    *               Maritime aerosol model                                        *
    *           optical condition identity :                                      *
    *               visibility :  8.49 km  opt. thick. 550 nm :  0.5000           *
    *                                                                             *
    *                       spectral condition                                    *
    *                       ------------------                                    *
    *            monochromatic calculation at wl 0.400 micron                     *
    *                                                                             *
    *                       Surface polarization parameters                       *
    *                       ----------------------------------                    *
    *                                                                             *
    *                                                                             *
    * Surface Polarization Q,U,Rop,Chi    0.00000  0.00000  0.00000     0.00      *
    *                                                                             *
    *                                                                             *
    *                       target type                                           *
    *                       -----------                                           *
    *           homogeneous ground                                                *
    *             monochromatic reflectance  1.000                                *
    *                                                                             *
    *                       target elevation description                          *
    *                       ----------------------------                          *
    *           ground pressure  [mb] 1013.00                                     *
    *           ground altitude  [km] 0.000                                       *
    *                                                                             *
    *                       plane simulation description                          *
    *                       ----------------------------                          *
    *           plane  pressure          [mb] 1013.00                             *
    *           plane  altitude absolute [km]  0.000                              *
    *                atmosphere under plane description:                          *
    *                ozone content             0.000                              *
    *                h2o   content             0.000                              *
    *               aerosol opt. thick. 550nm  0.000                              *
    *                                                                             *
    *                        atmospheric correction activated                     *
    *                        --------------------------------                     *
    *                        BRDF coupling correction                             *
    *           input apparent reflectance :  0.500                               *
    *                                                                             *
    *******************************************************************************
    
    
    
    *******************************************************************************
    *                                                                             *
    *                         integrated values of  :                             *
    *                         --------------------                                *
    *                                                                             *
    *       apparent reflectance  1.1287696  appar. rad.(w/m2/sr/mic)  588.646    *
    *                   total gaseous transmittance  1.000                        *
    *                                                                             *
    *******************************************************************************
    *                                                                             *
    *                         coupling aerosol -wv  :                             *
    *                         --------------------                                *
    *           wv above aerosol :   1.129     wv mixed with aerosol :   1.129    *
    *                       wv under aerosol :   1.129                            *
    *******************************************************************************
    *                                                                             *
    *                         integrated values of  :                             *
    *                         --------------------                                *
    *                                                                             *
    *       app. polarized refl.  0.0000    app. pol. rad. (w/m2/sr/mic)    0.000 *
    *             direction of the plane of polarization  0.00                    *
    *                   total polarization ratio     0.000                        *
    *                                                                             *
    *******************************************************************************
    *                                                                             *
    *                         int. normalized  values  of  :                      *
    *                         ---------------------------                         *
    *                      % of irradiance at ground level                        *
    *     % of direct  irr.    % of diffuse irr.    % of enviro. irr              *
    *               0.351               0.354               0.295                 *
    *                       reflectance at satellite level                        *
    *     atm. intrin. ref.   background  ref.  pixel  reflectance                *
    *               0.000               0.000               1.129                 *
    *                                                                             *
    *                         int. absolute values of                             *
    *                         -----------------------                             *
    *                      irr. at ground level (w/m2/mic)                        *
    *     direct solar irr.    atm. diffuse irr.    environment  irr              *
    *             648.957             655.412             544.918                 *
    *                      rad at satel. level (w/m2/sr/mic)                      *
    *     atm. intrin. rad.    background  rad.    pixel  radiance                *
    *               0.000               0.000             588.646                 *
    *                                                                             *
    *                                                                             *
    *                      sol. spect (in w/m2/mic)                               *
    *                                1663.594                                     *
    *                                                                             *
    *******************************************************************************
    
    
    
    
    
    *******************************************************************************
    *                                                                             *
    *                          integrated values of  :                            *
    *                          --------------------                               *
    *                                                                             *
    *                             downward        upward          total           *
    *      global gas. trans. :     1.00000        1.00000        1.00000         *
    *      water   "     "    :     1.00000        1.00000        1.00000         *
    *      ozone   "     "    :     1.00000        1.00000        1.00000         *
    *      co2     "     "    :     1.00000        1.00000        1.00000         *
    *      oxyg    "     "    :     1.00000        1.00000        1.00000         *
    *      no2     "     "    :     1.00000        1.00000        1.00000         *
    *      ch4     "     "    :     1.00000        1.00000        1.00000         *
    *      co      "     "    :     1.00000        1.00000        1.00000         *
    *                                                                             *
    *                                                                             *
    *      rayl.  sca. trans. :     0.84422        1.00000        0.84422         *
    *      aeros. sca.   "    :     0.94572        1.00000        0.94572         *
    *      total  sca.   "    :     0.79616        1.00000        0.79616         *
    *                                                                             *
    *                                                                             *
    *                                                                             *
    *                             rayleigh       aerosols         total           *
    *                                                                             *
    *      spherical albedo   :     0.23410        0.12354        0.29466         *
    *      optical depth total:     0.36193        0.55006        0.91199         *
    *      optical depth plane:     0.00000        0.00000        0.00000         *
    *      reflectance I      :     0.00000        0.00000        0.00000         *
    *      reflectance Q      :     0.00000        0.00000        0.00000         *
    *      reflectance U      :     0.00000        0.00000        0.00000         *
    *      polarized reflect. :     0.00000        0.00000        0.00000         *
    *      degree of polar.   :         nan           0.00            nan         *
    *      dir. plane polar.  :      -45.00         -45.00         -45.00         *
    *      phase function I   :     1.38819        0.27621        0.71751         *
    *      phase function Q   :    -0.09117       -0.00856       -0.04134         *
    *      phase function U   :    -1.34383        0.02142       -0.52039         *
    *      primary deg. of pol:    -0.06567       -0.03099       -0.05762         *
    *      sing. scat. albedo :     1.00000        0.98774        0.99261         *
    *                                                                             *
    *                                                                             *
    *******************************************************************************
    *******************************************************************************
    
    
    
    *******************************************************************************
    *                        atmospheric correction result                        *
    *                        -----------------------------                        *
    *       input apparent reflectance            :    0.500                      *
    *       measured radiance [w/m2/sr/mic]       :  260.747                      *
    *       atmospherically corrected reflectance                                 *
    *       Lambertian case :      0.52995                                        *
    *       BRDF       case :      0.52995                                        *
    *       coefficients xa xb xc                 :  0.00241  0.00000  0.29466    *
    *       y=xa*(measured radiance)-xb;  acr=y/(1.+xc*y)                         *
    

【问题讨论】:

    标签: python text idioms


    【解决方案1】:

    更完整、或许更健壮的解决方案需要使用使用自定义语法的解析器 (pyparsing) 或某种基于 FSM 的处理器 (TextFSM)。

    这两个选项都可以用于此输出。一个(可能)更轻量级的解决方案是根据已知标签识别每一行,然后适当地提取(如其他海报所建议的那样)。

    有几种方法可以实现这一点。我建议将“提取器”可调用对象映射到已知的行标签,然后迭代并调用匹配的提取器。每个可调用对象都将 line 和 context object/dict 作为参数,并根据需要将属性添加到 context。类似于https://gist.github.com/1035938

    【讨论】:

    • 我对 textFSM 的投票。他们有一个很好的教程,如果你通过它可以让你相对快速地学习。
    【解决方案2】:

    您可以使用自己的迷你语言,即自动提取。 我做了以下操作来自动解析专有程序输出

    # will match in the order written here
    tokens = ["num_ref_frames", "Max QP", "Min QP", "Avg QP", "I4x4",
              "I16x16", "SkipZero", "SkipMV", "16x16", "16x8", "8x16",
              "8x8", "8x4", "4x8", "4x4"]
    
    special = ["Quarterpel MVs"]
    
    # this dictionary (hash-table) contains the search string from tokens array
    # as well as an array where the first element is the field to extract to
    # create matrix array. e.g. 0 = 1st field, 1 = 2nd field, 3 = 3rd field etc.
    dict = {tokens[0]:  [1], tokens[1]:  [1], tokens[2]:  [1], tokens[3]:  [1],
            tokens[4]:  [2], tokens[5]:  [2], tokens[6]:  [2], tokens[7]:  [2],
            tokens[8]:  [2], tokens[9]:  [2], tokens[10]: [2], tokens[11]: [2],
            tokens[12]: [2], tokens[13]: [2], tokens[14]: [2],}
    

    然后我简单地循环输入,并为每一行检查 token 的内容;如果找到匹配项,我会根据 dict-entry 进行拆分以提取正确的字段。

    special 上面是处理,一个特殊的变量,需要从多行读取。

    更新

    克隆 git://gist.github.com/1037403.git 以获取代码副本

    usage:
    ./parser.py all_dec.txt
    

    希望对你有帮助!

    【讨论】:

    • 听起来某种 DSL 在这里可以很好地工作。
    • 这看起来是个不错的解决方案。你能发布完整的代码吗? (我建议把它放在像 gist.github.com 这样的地方)。谢谢!
    • 请记住,此解决方案假定每行都有标签和数据。作为通用解决方案,我会继续这样做,并使用带有{'match': (parser_function, params)...} 的字典,并为每行匹配执行带有 line+params 的 parser_function。
    • @robintw 用 gist-link 更新了我的帖子。抱歉,昨天的团队建设活动耽搁了:-)
    【解决方案3】:

    如果您想要一个通用解析库,可以使用 pyparsing,但在这种情况下可能会有点过分。

    这似乎是一个相当以行为导向的文本文件,它的大小并没有那么大,所以最好的办法是遍历每一行,寻找能够识别你所追求的东西的文本。

    比如:

    lines = open('file.txt', 'r')
    for n, line in enumerate(lines):
        if 'direct solar irr.    atm. diffuse irr.    environment  irr' in line:
            values = lines[n+1].split() # after the next line after this one
            self.irradiance_direct, self.irradiance_diffuse, self.irradiance_env = values
    

    然后您可以根据需要添加更多 if 语句等以获取其他数据。尽管如果您有大量数据,您可能希望对代码进行一些概括。 (可能是一个字典,其中包含要匹配的文本作为键以及匹配键时要调用的函数。

    您可能还想使用正则表达式来匹配该行,以便更好地处理不同数量的空白。否则只是一个空格太多或太少都会把它扔掉。

    【讨论】:

      【解决方案4】:

      恕我直言,最好的方法是使用 mmaped 文件,然后使用正则表达式查找您要查找的内容。

       text = mmap.mmap(file)
       re.sub(pattern, text)
      

      Mmap 模块将文件映射为文本,因此您几乎可以对字符串执行任何操作。正则表达式是搜索内容的最佳方式。简单高效。

      【讨论】:

        【解决方案5】:

        如果您需要查找特定的行,只需将所有内容都作为字符串处理并运行特定的正则表达式来挖掘您的宝石。

        如果您需要提取更多数据,我相信只需少量工作即可为您的数据制作一个不错的解析器。我会使用以下函数作为开始:

        def extract_screens(text):
            """ 
            Returns a list of screens (divided by astericks).
            Each screen is a list of strings stripped from asterisks.
            """
            ...
        
        def process_screen(screen):
            """ 
            Returns a list of screen divisions as tuples: [(heading, body)...]
            heading is a string, body is a list of strings
            blank lines are filtered out.
            """
            ...
        

        现在你应该有一个文本片段的索引列表。您可以遍历它们并为每个部分执行一个简单而特定的特殊解析器方法。

        提示:使用单元测试让自己保持清醒。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-24
          • 1970-01-01
          • 2014-06-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多