I have created a python program that prints a vertical bar graph made from fields and values inputted by the user. It works by first creating a horizontal bar graph and then going through each layer and determining whether to print a letter, a "|"
, a "_"
, or a space. I would appreciate any feedback on the program and things I could do to improve it.
import re
feilds = input("Input| ex: dogs,10 cats,23 birds,67\n").strip()
while not re.match("^(\w+,\d+ ?)+$", feilds):
feilds = input("invalid input, use this format:\nfeild,value feild,value feild,value...\n").strip()
width = int(input("How wide is your output window in characters? "))
scale = float(input("Scale: "))
vals = dict([feild.split(",") for feild in feilds.split(" ")])
for k, v in vals.items():
vals[k] = int(v)
spacing = int(width / len(vals.keys()))
horizontal = ["-" * int(v * scale) + "|" + k[::-1] for k, v in vals.items()]
vertical = []
for x in reversed(range(len(max(horizontal, key=len)))):
layer = []
for val in horizontal:
try:
if val[x] == "-":
layer.append("|")
elif val[x] == "|":
layer.append("_")
else:
layer.append(val[x])
except IndexError:
layer.append(" ")
vertical.append(layer)
print("\n")
print("\n".join((" " * (spacing - 1)).join(layer) for layer in vertical))
ex:
input:
dogs,20 cats,18 fish,25 birds,10
80
.5
output:
f
i
d s
o c h
g a _
s t |
_ s | b
| _ | i
| | | r
| | | d
| | | s
| | | _
| | | |
| | | |
| | | |
| | | |
| | | |
NOTE: output might be messed up if the width is off by a lot. Make sure to input a width close to what it is.