2010-01-31 83 views
4

我無法使用python reg exp從文件中讀取數據。使用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'。

我有2個問題:

  1. 是否有可能獲得所有的點用一個表達或者我通過每行需要循環,並尋找開始結束?當我嘗試找到該部分並在單個表達式中讀取點時,我似乎無法使reg exp工作。
  2. 如何解析工程記號中的數字?

我找不到與我正在做的事情非常接近的例子。如果它在那裏,請將它指向我。

回答

3

我想這會讓你得到你想要的。只要文件一致。

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

「$ F」?你一直在觸摸PHP,是不是。 – 2010-01-31 03:58:39

+0

是:(很痛, – 2010-01-31 04:01:54

+0

非常優雅,但是如果文件後面包含數據,它會繼續收集「Y」後的值 - 如果沒有,那麼這是完美的 – 2010-01-31 08:54:21

0

幾乎沒有一樣優雅的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'))] 
1
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