This repository has been archived by the owner on Apr 14, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
csvbar.py
61 lines (55 loc) · 2.03 KB
/
csvbar.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# coding: utf-8
import argparse
import locale
import csv
import sys
import io
import os
def main():
locale.setlocale(locale.LC_ALL, '')
try:
args = arguments()
labels, data = read(args['FILE'])
display(labels, data, args['width'])
except BaseException as e: sys.exit(e)
def arguments():
parser = argparse.ArgumentParser(description='draw bar graphs from CSV files in the terminal')
parser.add_argument('FILE', nargs='?', default='-', help='the CSV file to operate on -- if omitted, will accept input on STDIN')
parser.add_argument('-w', '--width', type=int, default=50, help='width of graph in characters (default is 50)')
args = vars(parser.parse_args())
if args['FILE'] == '-' and sys.stdin.isatty():
parser.print_help(sys.stderr)
parser.exit(1)
return args
def read(filename):
labels = []
data = []
if not os.path.isfile(filename) and filename != '-': raise Exception(filename + ': no such file')
file = sys.stdin if filename == '-' else io.open(filename, 'r')
reader = csv.reader(file)
headers = next(reader) # skip these
for line in reader:
labels.append(line[0])
try: data.append(float(line[1]))
except ValueError: raise Exception(line[1] + ' is not a number')
file.close()
return labels, data
def display(labels, data, width):
full_tick = '█'
half_tick = '▌'
total = sum(data)
step = max(data) / width
spacing = max(len(label) for label in labels)
print('')
for i in range(len(data)):
label = labels[i]
count = data[i]
padding = ' ' * (spacing - len(label) + 2)
bar = half_tick if count < step else int(count / step) * full_tick
number = locale.format('%.2f', count, grouping=True)
percentage = locale.format('%.2f', count / total * 100, grouping=True)
print(label + padding + bar + ' ' + number + ' (' + percentage + '%)')
print('')
print('Total: ' + locale.format('%.2f', total, grouping=True))
if __name__ == '__main__':
main()