To check out this repository please hg clone the following URL, or open the URL using EasyMercurial or your preferred Mercurial client.
root / python-intro.py @ 6:4ec6aa30a1f8
History | View | Annotate | Download (896 Bytes)
| 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 |
source = open('data.txt', 'r') |
| 30 |
|
| 31 |
number_of_marlins = 0
|
| 32 |
|
| 33 |
# count number of data records
|
| 34 |
for line in source: |
| 35 |
if is_data(line) == True: |
| 36 |
number_of_marlins = number_of_marlins + count_marlins(line) |
| 37 |
|
| 38 |
source.close() |
| 39 |
|
| 40 |
print "Total number of marlins:", number_of_marlins |