Last active
May 6, 2020 01:55
-
-
Save seanlaw/76799c699cd96d655e704d16fa3bc58f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import argparse | |
def parse_orders(fname, outname=None, encoding="Windows-1252"): | |
if outname is not None: | |
fout = open(outname, "w") | |
with open(fname, encoding=encoding) as f: | |
date = None | |
check = None | |
quantity = None | |
item = None | |
price = None | |
for line in f: | |
line = line.strip() | |
tokens = line.split() | |
# Date | |
if len(tokens) >= 2 and tokens[0].startswith("Date"): | |
date = tokens[1] | |
# Check | |
if len(tokens) >= 2 and tokens[0].startswith("Check"): | |
check = tokens[2] | |
if date is not None and check is not None: | |
# Quantity, Item | |
if len(tokens) >= 3 and tokens[1] == "X": | |
quantity = tokens[0] | |
if tokens[-1].startswith("$"): | |
item = " ".join(tokens[2:-1]) | |
price = tokens[-1][1:] | |
else: | |
item = " ".join(tokens[2:]) | |
if len(tokens) >= 1 and tokens[0].startswith("$"): | |
# Price | |
price = tokens[0][1:] | |
# Print output and reset | |
if quantity is not None and item is not None and price is not None: | |
out = f'"{date}","{check}","{quantity}","{item}","{price}"' | |
if outname is not None: | |
fout.write(out + "\n") | |
else: | |
print(out) | |
quantity = None | |
item = None | |
price = None | |
# Subtotal | |
if len(tokens) >= 1 and tokens[0].startswith("Subtotal"): | |
check = None | |
date = None | |
if outname is not None: | |
fout.close() | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser() | |
parser.add_argument("-out", help="Specify an output file name", default=None) | |
parser.add_argument("inp", help="Specify an input file to parse") | |
args = parser.parse_args() | |
parse_orders(args.inp, args.out) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From the command line, you can do: