Using Python Reg Exp to read data from a file

I am having problems using python reg exp to read data from a file.

The file has data that I want, and some information that I am not interested in. Below is an example of the information that interests me. The number of rows will vary

FREQ VM(VOUT) 1.000E+00 4.760E+01 1.002E+00 4.749E+01 Y 

I want to create a list of tuples like:

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

I try to read the file until I find the line "FREQ VM (VOUT)" and read the data until I press "Y".

I have 2 questions:

  • Is it possible to get all points with one expression or do I need to scroll through each line and look for the beginning? I can't seem to get reg exp to work when I try to find the section and read the points in the same expression.
  • How to parse a number contained in technical notation?

I could not find an example that was very close to what I was doing. If he is there, please indicate him to me.

+4
source share
3 answers

I think this will give you what you want. While the file is consistent.

 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'] 

If you want it to break into "Y", make it less elegant:

 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]))) 
+3
source
 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 
+1
source

Not as elegant as Tor's answer . There are also no regular expressions. Bring it down!

 #!/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() 

Returns:

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

Source: https://habr.com/ru/post/1299856/


All Articles