read lines
Zepo Len
no at no.no
Tue Dec 4 08:12:50 EST 2007
> Hi, I have a text file like this;
>
> 1 -33.453579
> 2 -148.487125
> ....
>
> So I want to write a program in python that reads each line and
> detects which numbers of the second column are the maximum and the
> minimum.
>
> I tried with;
>
> import os, sys,re,string
>
> # first parameter is the name of the data file
> name1 = sys.argv[1]
> infile1 = open(name1,"r")
>
> # 1. get minimum and maximum
>
> minimum=0
> maximum=0
>
>
> print " minimum = ",minimum
> print " maximum = ",maximum
>
>
> while 1:
> line = infile1.readline()
> ll = re.split("\s+",string.strip(line))
> print ll[0],ll[1]
> a=ll[0]
> b=ll[1]
> print a,b
> if(b<minimum):
> minimum=b
> print " minimum= ",minimum
> if(b>maximum):
> maximum=b
> print " maximum= ",maximum
>
> print minimum, maximum
>
>
> But it does not work and I get errors like;
>
> Traceback (most recent call last):
> File "translate_to_intervals.py", line 20, in <module>
> print ll[0],ll[1]
> IndexError: list index out of range
Your regex is not working correctly I guess, I don't even know why you are
using a regex, something like this would work just fine:
import sys
nums = [float(line.split(' -')[1]) for line in open(sys.argv[1])]
print 'min=', min(nums), 'max=', max(nums)
More information about the Python-list
mailing list