[Tutor] counting problem

Kent Johnson kent37 at tds.net
Mon Aug 1 22:22:09 CEST 2005


cgw501 at york.ac.uk wrote:
> hi,
> 
> I have large txt file with lines like this:
> 
> ['DDB0216437']	1166	1174	9     ZZZ   100
> 
> What I want to do is quickly count the number of lines that share a value 
> in the 4th column and 5th (i.e. in this line I would count all the line 
> that have '9' and 'ZZZ'). Anyone got any ideas for the quickest way to do 
> this? The solution I have is really ugly. thanks,

This should get you started. It assumes that there is no whitespace embedded in the fields. Add error handling and options to taste.

Kent

count = 0
f = open('data.txt')
for line in f:
  data = line.split()
  if data[3] == '9' and data[4] == 'ZZZ':
    count += 1
f.close()
print count



More information about the Tutor mailing list