Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to match a text format to a string without regex in python?

I am reading a file with lines of the form exemplified by

[ 0 ] L= 9 (D) R= 14 (D) p= 0.0347222 e= 10 n= 34

I saw Matlab code to read this file given by

[I,L,Ls,R,Rs,p,e,n] = textread(f1,'[ %u ] L= %u%s R= %u%s p= %n e=%u n=%u')

I want to read this file in Python. The only thing I know of is regex, and reading even a part of this line leads to something like

re.compile('\s*\[\s*(?P<id>\d+)\s*\]\s*L\s*=\s*(?P<Lint>\d+)\s*\((?P<Ltype>[DG])\)\s*R\s*=\s*(?P<Rint>\d+)\s*')

which is ugly! Is there an easier way to do this in Python?

like image 677
highBandWidth Avatar asked Feb 24 '23 12:02

highBandWidth


2 Answers

You can make the regexp more readable by building it with escape/replace...

number = "([-+0-9.DdEe ]+)"
unit = r"\(([^)]+)\)"
t = "[X] L=XU R=XU p=X e=X n=X"
m = re.compile(re.escape(t).replace("X", number).replace("U", unit))
like image 96
6502 Avatar answered Feb 27 '23 01:02

6502


This looks more or less pythonic to me:

line = "[ 0 ] L= 9 (D) R= 14 (D) p= 0.0347222 e= 10 n= 34"

parts = (None, int, None,
         None, int, str,
         None, int, str,
         None, float,
         None, int,
         None, int)

[I,L,Ls,R,Rs,p,e,n] = [f(x) for f, x in zip(parts, line.split()) if f is not None]

print [I,L,Ls,R,Rs,p,e,n]
like image 29
abbot Avatar answered Feb 27 '23 00:02

abbot