Stdin Stdout python
Question: For my work i'm used to work with matlab. No i try to learn the basic skills
of python as well. Currently I'm working on on the following excersise:

> You are interested in extracting all of the occurrences that look like this
>
> `<Aug22-2008> <15:37:37> Bond Energy LDA -17.23014168 eV`
>
> In particular, you want to gather the numerical values (eg, `-17.23014168`),
> and print them out. Write a script that reads the output file from standard
> input, and uses regular expressions to locate the values you want to
> extract. Have your script print out all the values to standard output.

This is the code I use:

    
    
    import os,re
    from string import rjust
    
    dataEx=re.compile(r'''
        ^\s*
        <Aug22-2008>
        \s+
        <\d{2}:\d{2}:\d{2}>
        \s+
        Bond
        \s
        Energy 
        \s
        LDA 
        \s+
        ((\+|-)?(\d*)\.?\d*)   
    
        ''',re.VERBOSE)
    
    
    
    
    f=open('Datafile_Q2.txt','r') 
    line = f.readline()
    while line != '':
     line = f.readline() # Get next line
     m = dataEx.match(line)
     if m:
       # print line
        print m.group(1) 
    

With this code I'm able to find all values in the datafile they ask for.
However I do have a few questions. Firstly, they ask specific something about
stdin and stdout. No I'm wondering do I use the right code to read the output
file from standard input and do I really print out all the values to standard
output in this way? Futhermore, I'm wondering whether there is a better or
more easy way to find the required values?


Answer: To find the numbers your looking for I would use a positive lookbehind and
lookahead function in your regular expression.

    
    
    (?<=Bond Energy LDA ).*(?= eV)
    

This checks to see if the thing you are looking at is proceeded by 'Bond
Energy LDA' and followed by 'eV' but does not include them in the string you
extract. So assuming that the numbers you are looking for are always proceeded
and followed by those two things you can find them like that.

A nice way to read from stdin is to use the sys python module.

    
    
    import sys
    

Then you can read lines straight from stdin:

    
    
    import sys
    import re    
    
    from line in sys.stdin:
        matchObj = re.search(r '(?<=Bond Energy LDA ).*(?= eV)', line, re.I)
        if(matchObj):
            print(matchObj.group())
    

If the regular expression is not found on the line then matchObj will be null
skipping the if statement. If it is found the search will return a matchObj
containing groups. You can then print the group to stdout as print will by
default print to stdout if no file is given.

