Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def main():
- fh = openFile('NFL2011QB.csv')
- fd = readFile(fh)
- fh.close
- floatFields = []
- intFields = []
- headers = getHeaders(fd)
- parseData(fd, headers)
- typeCastFloatFields(fd, floatFields)
- typeCastIntFields(fd, intFields)
- print(fd)
- def tdReport(L):
- L.sort(key=tdKey)
- L.reverse()
- for item in L:
- print(item['TD '])
- def tdKey(line):
- return line['TD ']
- def typeCastFloatFields(L, fields):
- '''
- (list of dicts by field keys) -> list
- Casts dictionary key values to floats if possible
- '''
- for ix in range(len(L)):
- for field in fields:
- L[ix][field] = float(L[ix][field])
- return L
- def typeCastIntFields(L, fields):
- '''
- (list of dicts by field keys) -> list
- Casts dictionary key values to integers if possible
- '''
- for ix in range(len(L)):
- for field in fields:
- L[ix][field] = int(L[ix][field])
- return L
- def conditionFields(field):
- if len(field) == 0 or '':
- return 0
- try:
- return int(field)
- except:
- try:
- return float(field)
- except:
- return field
- def readFile(fh):
- '''
- (textIOWrapper / file handle) -> list of strings
- Reads files into lists by lines with readlines(),
- Strips off white space if any with strip()
- Removes likes with no data with pop()
- '''
- L = fh.readlines()
- for ix in range(len(L)):
- L[ix] = L[ix].strip()
- for ix in range(len(L)-1, -1, -1):
- if len(L[ix]) == 0:
- L.pop(ix)
- return L
- def openFile(fname):
- '''
- (str) ->textIOWrapper and file handler. None if error.
- '''
- return open(fname, 'r')
- def getHeaders(L):
- '''
- (List) -> list of parsed header values.
- Pops the first line, return as comas delimited headers
- '''
- hl = L.pop(0)
- return hl.split(',')
- def parseDataLines(s):
- '''
- (str of csv) -> list of values
- Brings strings into fields and removes unwanted commas.
- '''
- L = s.split(',')
- if len(L) > 21:
- L[20] = L[20] + ',' + L[21]
- L.pop(20)
- if len(L) > 21:
- L[20] = L[20] + ',' + L[21]
- L.pop(20)
- L[20] = L[20][1:-1]
- return L
- def parseData(L, headers):
- '''
- (List of values, headers)
- takes list data and breaks items down into lists
- '''
- for ix in range(len(L)):
- L[ix] = parseDataLines(L[ix])
- L[ix] = makeDicts(L[ix], headers)
- def makeDicts(L, headers):
- '''
- (list, list of headers) -> dictionary of headers and data
- Converts list to dictionary with header values as keyes
- '''
- D = {}
- for ix in range(len(headers)):
- D[headers[ix]] = L[ix]
- return D
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement