<br><div><span class="gmail_quote">On 10/22/07, <b class="gmail_sendername">wang frank</b> <<a href="mailto:fw3@hotmail.co.jp">fw3@hotmail.co.jp</a>> wrote</span><blockquote class="gmail_quote" style="margin:0;margin-left:0.8ex;border-left:1px #ccc solid;padding-left:1ex">
<div>
 <br>
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:<br>
 <br>
x1 =<br>
 <br>
    0.1<br>
 <br>
y =<br>
 <br>
   7<br>
 <br>
z = <br>
 <br>
   6.7<br>
 <br>
x1 =<br>
 <br>
   0.5<br>
 <br>
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<br>
 <br>
x1 = 0.1<br>
x1 = 0.5.<br> </div></blockquote></div><div><br class="webkit-block-placeholder"></div>Here is a fairly naive version with re named groups that should handle the example you pasted.<div><br class="webkit-block-placeholder">
</div><div><div><div>In [62]: import re</div><div><br class="webkit-block-placeholder"></div><div>In [63]: px = re.compile('(?P<variable>\w+)\s=\s+(?P<value>\d.*\d*)')</div><div><br class="webkit-block-placeholder">
</div><div>In [64]: for var in px.finditer(s):</div><div>    print "%s = %s" %(var.group('variable'), var.group('value'))</div><div>   ....:     </div><div>   ....:     </div><div>a = 0.1</div><div>
y = 7</div><div>z = 6.7</div><div>x1 = 0.5</div></div><div><br class="webkit-block-placeholder"></div><div>To filter for only the x1's just test for the group named 'variable':</div><div><br class="webkit-block-placeholder">
</div><div><div>In [66]: for var in px.finditer(s):</div><div>   ....:     if var.group('variable')=='x1':</div><div>   ....:         print "%s = %s" %(var.group('variable'), var.group('value'))
</div><div>   ....:         </div><div>   ....:         </div><div>x1 = 0.5</div></div><div><br class="webkit-block-placeholder"></div><div>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 
<a href="http://pyparsing.wikispaces.com/">http://pyparsing.wikispaces.com/</a> and regular expressions.</div></div><div><div><br class="webkit-block-placeholder"></div><div><br> </div><div><br>-- <br>Travis Brady<br><a href="http://travisbrady.com/">
http://travisbrady.com/</a>
</div></div>