Skip to content

Instantly share code, notes, and snippets.

@colehocking
Created December 23, 2018 20:25
Show Gist options
  • Select an option

  • Save colehocking/f4a41aaadc3f2a0969ca4b92fc129993 to your computer and use it in GitHub Desktop.

Select an option

Save colehocking/f4a41aaadc3f2a0969ca4b92fc129993 to your computer and use it in GitHub Desktop.
Get the summation of dollar amounts found in a text file
#!/usr/bin/env python
# Calculate dollar values of a text file with python
# -- Cole Hocking
import re
from sys import argv, exit
import os.path as opath
def validateFile(filei):
"""
Check for file_exists
"""
if opath.isfile(filei):
return True
else:
print("%r not found" % (filei))
exit(1)
def getValue(file_name):
"""
Returns the total
"""
# Dollar value '\d' is decimal
pattern = re.compile("\$[0-9]+(?:,{1}[0-9]+)*(?:\.\d{2})?")
with open(file_name, "r") as sFile:
total = 0
for line in sFile:
#lineNo = sFile.index(line)
nums = pattern.findall(line)
for n in nums:
# s is now the list of the splits; we want the 0 position
print("Found: %s" % n)
# Take the dollars out for valid float
n = n.replace('$', '')
# Take the commas out too
n = n.replace(',', '')
s = float(n) # convert to float
total += s
return total
def main(argv):
if len(argv) != 2:
print("Usage: ./text_calc.py <file-to-parse>")
exit(1)
assert(validateFile(argv[1]))
total = getValue(argv[1])
print("-----------------------")
print("Total value is ${:,.2f}".format(total))
if __name__ == "__main__":
main(argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment