reading a column from text

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Abhishes
    New Member
    • Jun 2012
    • 1

    reading a column from text

    Hi I have large text file as follows.

    EXPERIMENT : KSAS1201 SG CLIMAT CHANGE STUDY ON KANSAS
    DATA PATH : C:\DSSAT45\Sorg hum\
    TREATMENT 1 : N.American SGCER045



    @ VARIABLE SIMULATED MEASURED
    Panicle Initiation day (dap) 62 -99
    Anthesis day (dap) 115 -99
    Physiological maturity day (dap) 160 -99
    Yield at harvest maturity (kg [dm]/ha) 8478 -99
    Number at maturity (no/m2) 32377 -99 Unit wt at maturity (g [dm]/unit) 0.0262 -99

    I wish to read only a certain column from this file such as just a column below simulation and measured
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    Hi

    We often like to see the code you've attempted so far, what results you've got and what you're looking for.

    However, the simple way to do this is to use regular expressions.

    For example:
    Code:
    import re
    myFile=open("input.txt")
    
    result={}   # dictionary for results  
    p=re.compile(r'(.*) (.*) (.*)')
    start=False
    for line in myFile:
        if not start: #continue until the data starts
            if line[0]=="@":
                start=True
            continue
        m=p.match(line)
        result[m.group(1)] = [float(m.group(2)),float(m.group(3))]
    
    for k in result:
        print "##############"
        print "key:",k
        print "value:",result[k]
    uses the fact that regular expressions are by default hungry, and therefore finds the last two spaces in the lines. This yields the following:
    Code:
    >>> 
    ##############
    key: Unit wt at maturity (g [dm]/unit)
    value: [0.0262, -99.0]
    ##############
    key: Physiological maturity day (dap)
    value: [160.0, -99.0]
    ##############
    key: Yield at harvest maturity (kg [dm]/ha)
    value: [8478.0, -99.0]
    ##############
    key: Anthesis day (dap)
    value: [115.0, -99.0]
    ##############
    key: Number at maturity (no/m2)
    value: [32377.0, -99.0]
    ##############
    key: Panicle Initiation day (dap)
    value: [62.0, -99.0]
    >>>

    Comment

    Working...