【问题标题】:Using Python Reg Exp to read data from file使用 Python Regex 从文件中读取数据
【发布时间】:2010-01-31 03:31:35
【问题描述】:

我在使用 python reg exp 从文件中读取数据时遇到问题。

该文件包含我想要的数据和一些我不感兴趣的信息。我感兴趣的信息示例如下。行数会有所不同

FREQ VM(VOUT)        

1.000E+00  4.760E+01

1.002E+00  4.749E+01
Y

我想创建一个元组列表,例如:

[(1.000, 47.6),(1.002, 47.49)]

我正在尝试读取文件,直到找到“FREQ VM(VOUT)”行并读取数据点,直到找到“Y”为止。

我有两个问题:

  1. 是否可以用一个表达式获得所有点,还是我需要遍历每一行并寻找起点?当我尝试查找该部分并读取单个表达式中的点时,我似乎无法让 reg exp 工作。
  2. 如何解析工程符号中的数字?

我找不到与我正在做的事情非常接近的示例。如果有,请指点一下。

【问题讨论】:

    标签: python regex


    【解决方案1】:

    我认为这会让你得到你想要的。只要文件一致。

    from csv import reader
    with open('file') as f:
      listoftuples = [(float(row[0]), float(row[1])) 
                      for row in reader(f, delimiter='  ') 
                      if row and row[0] != 'FREQ']
    

    如果你想让它在“Y”处中断,那就做这个不太优雅的事情:

    from csv import reader
    l = []
    with open('file') as f:
      for row in reader(f, delimiter='  '):
        if row[0] == 'Y':
          break
        if row and row[0] != 'FREQ':
          l.append((floar(row[0]), float(row[1])))
    

    【讨论】:

    • "$f"?你又开始接触 PHP 了,不是吗。
    • 非常优雅。但是,如果文件后面包含数据,它将继续收集“Y”之后的值 - 如果没有,那么这是完美的。
    【解决方案2】:
    import decimal
    flag=0
    result=[]
    for line in open("file"):
        line=line.rstrip()
        if line == "Y": flag=0
        if line.startswith("FREQ VM"):
             flag=1
             continue
        if flag and line:
             result.append(map(decimal.Decimal,line.split()))
    print result
    

    【讨论】:

      【解决方案3】:

      不如Tor's answer 优雅。也没有正则表达式。投反对票!

      #!/usr/bin/env python
      # -*- coding: utf-8 -*-
      
      import decimal
      import os
      
      def main():
          we_care = False # start off not caring 
      
          list_of_tuples = []
      
          f = open('test.txt','r')
      
          for line in f:
              if line.startswith('FREQ'):
                  we_care = True # we found what we want; now we care
                  continue
              if we_care:
                  try:
                      x,y = (decimal.Decimal(x) 
                              for x in line.rstrip(os.linesep).split())
                      list_of_tuples.append((x,y))
                  except ValueError:
                      pass # we get here when a line doesn't contain two floats
                  except decimal.InvalidOperation:
                      pass # we get here when a line contains a non-decimal
                  if line.startswith('Y'):
                      break # break out of processing once you've got your data
          return list_of_tuples
      
      if __name__ == "__main__":
          print main()
      

      返回:

      [(Decimal('1.000'), Decimal('47.60')), (Decimal('1.002'), Decimal('47.49'))]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-04
        • 1970-01-01
        • 2013-03-23
        • 2017-02-05
        相关资源
        最近更新 更多