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?
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))
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With