extract certain values from file with re
Matteo
mahall at ncsa.uiuc.edu
Fri Oct 6 16:16:13 EDT 2006
Fabian Braennstroem wrote:
> Hi,
>
> I would like to remove certain lines from a log files. I had
> some sed/awk scripts for this, but now, I want to use python
> with its re module for this task.
>
> Actually, I have two different log files. The first file looks
> like:
>
> ...
> 'some text'
> ...
>
> ITER I----------------- GLOBAL ABSOLUTE RESIDUAL -----------------I I------------ FIELD VALUES AT MONITORING LOCATION ----------I
> NO UMOM VMOM WMOM MASS T EN DISS ENTH U V W P TE ED T
> 1 9.70E-02 8.61E-02 9.85E-02 1.00E+00 1.61E+01 7.65E+04 0.00E+00 1.04E-01-8.61E-04 3.49E-02 1.38E-03 7.51E-05 1.63E-05 2.00E+01
> 2 3.71E-02 3.07E-02 3.57E-02 1.00E+00 3.58E-01 6.55E-01 0.00E+00 1.08E-01-1.96E-03 4.98E-02 7.11E-04 1.70E-04 4.52E-05 2.00E+01
...
Just a thought, but what about using exceptions - something like:
for line in logfile:
vals=line.split()
try:
no=int(vals[0])
# parse line as needed
except ValueError: #first item is not a number
pass # ignore line, or parse it
separately
Coming from C++, using exceptions in this way still feels a bit creepy
to me, but I've been assured that this is very pythonic, and I'm slowly
adopting this style in my python code.
Parsing the line can be easy too:
(umom,vmom,wmom,mass...) = map(float,vals[1:])
-matt
More information about the Python-list
mailing list