Skip to content

Instantly share code, notes, and snippets.

@jonalmeida
Created October 2, 2018 17:13
Show Gist options
  • Save jonalmeida/c62984789477c8128a67cc2aa32ed331 to your computer and use it in GitHub Desktop.
Save jonalmeida/c62984789477c8128a67cc2aa32ed331 to your computer and use it in GitHub Desktop.
Get the total spent from an exported CSV on Presto (prestocard.ca)
#!/usr/bin/env python3
import csv, sys, re
from functools import reduce
"""
From StackOverflow: https://stackoverflow.com/a/32486472
Strips whitespace off from the headers of CSV field names.
"""
class DictReaderStrip(csv.DictReader):
@property
def fieldnames(self):
if self._fieldnames is None:
# Initialize self._fieldnames
# Note: DictReader is an old-style class, so can't use super()
csv.DictReader.fieldnames.fget(self)
if self._fieldnames is not None:
self._fieldnames = [name.strip() for name in self._fieldnames]
return self._fieldnames
def extract_value(s):
return float(re.search(r'([£\$€])(\d+(?:\.\d{2})?)'
, s).groups()[1])
"""
Main
"""
print('File: ' + sys.argv[1])
with open(sys.argv[1], 'r') as csvfile:
print(reduce( # Add them up and print!
lambda acc, x: acc + x,
map( # Take only the amount values
lambda x: extract_value(x['Amount']),
filter( # Filter out top-ups
lambda x: x['Type'] != 'Load Amount',
DictReaderStrip(csvfile)
)
)
))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment