Revision 0:15b82ccc064b
| data.txt | ||
|---|---|---|
| 2 | 2 |
2012.04.28,marlin,2 |
| 3 | 3 |
2012.04.28,turtle,1 |
| 4 | 4 |
2012.04.28,shark,3 |
| 5 |
# I think it was a Marlin... luis |
|
| 6 | 5 |
2012.04.27,marlin,4 |
| python-intro.py | ||
|---|---|---|
| 1 |
def is_data(line): |
|
| 2 |
""" Returns true if the line has data |
|
| 3 |
and false otherwise (header, comments, etc)""" |
|
| 4 |
|
|
| 5 |
answer = True |
|
| 6 |
|
|
| 7 |
if line.startswith('#'):
|
|
| 8 |
# skip comments |
|
| 9 |
answer = False |
|
| 10 |
elif line.startswith('D'):
|
|
| 11 |
# skip title row |
|
| 12 |
answer = False |
|
| 13 |
else: |
|
| 14 |
answer = True |
|
| 15 |
return answer |
|
| 16 |
|
|
| 17 |
|
|
| 18 |
def count_marlins(data): |
|
| 19 |
"""Receives a line of data and returns the count of Marlins in that line (zero otherwise)""" |
|
| 20 |
|
|
| 21 |
date, species, count = data.split(",")
|
|
| 22 |
marlins = 0 |
|
| 23 |
if species == "marlin": |
|
| 24 |
marlins = count |
|
| 25 |
return int(marlins) |
|
| 26 |
|
|
| 27 |
|
|
| 28 |
# script starts here... |
|
| 29 | 1 |
source = open('data.txt', 'r')
|
| 30 |
|
|
| 31 |
number_of_marlins = 0 |
|
| 32 |
|
|
| 33 |
# count number of data records |
|
| 34 | 2 |
for line in source: |
| 35 |
if is_data(line) == True: |
|
| 36 |
number_of_marlins = number_of_marlins + count_marlins(line) |
|
| 37 |
|
|
| 3 |
print line |
|
| 38 | 4 |
source.close() |
| 39 |
|
|
| 40 |
print "Total number of marlins:", number_of_marlins |
|
Also available in: Unified diff