Extract value and average

Tim Chase python.list at tim.thechases.com
Mon Jun 8 12:36:52 EDT 2009


> I would like to extract values corresponding to variable DIHED (here
> 4660.1650) and getting also the mean value from all DIHED.

To just pull the DIHED values, you can use this:

   import re
   find_dihed_re = re.compile(r'\bDIHED\s*=\s*([.-e\d]+)', re.I)
   total = count = 0
   for line in file('file.txt'):
     m = find_dihed_re.search(line)
     if m:
       str_value = m.group(1)
       try:
         f = float(str_value)
         total += f
         count += 1
       except:
         print "Not a float: %s" % str_value
   print "Total:", total
   print "Count:", count
   if count:
     print "Average:", total/count

If you want a general parser for the file, it takes a bit more work.

-tkc







More information about the Python-list mailing list