On 10/22/07, wang frank <[EMAIL PROTECTED]> wrote
>
>
> I have a big log file generated from matlabe, for each variable, it print
> the name of the variable and an empty line and then the value. such as:
>
> x1 =
>
>     0.1
>
> y =
>
>    7
>
> z =
>
>    6.7
>
> x1 =
>
>    0.5
>
> I want to use python to parse the file and selectively print out the
> vairable and its value. For example, I want to print out all the value
> related with x1, so the output will be
>
> x1 = 0.1
> x1 = 0.5.
>
>

Here is a fairly naive version with re named groups that should handle the
example you pasted.
In [62]: import re

In [63]: px = re.compile('(?P<variable>\w+)\s=\s+(?P<value>\d.*\d*)')

In [64]: for var in px.finditer(s):
    print "%s = %s" %(var.group('variable'), var.group('value'))
   ....:
   ....:
a = 0.1
y = 7
z = 6.7
x1 = 0.5

To filter for only the x1's just test for the group named 'variable':

In [66]: for var in px.finditer(s):
   ....:     if var.group('variable')=='x1':
   ....:         print "%s = %s" %(var.group('variable'), var.group
('value'))
   ....:
   ....:
x1 = 0.5

But I'm betting these files get more complex than just the snippet you
included, in which case it's probably worth looking at pyparsing
http://pyparsing.wikispaces.com/ and regular expressions.




-- 
Travis Brady
http://travisbrady.com/
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to