from os import strerror


file_name = "lab43.txt"

letters = {}

try:

    source = open(file_name, "rt", encoding="utf-8")

    ch = source.read(1)
    while ch != "":
        ch = ch.lower()

        if "a" <= ch <= "z":
            if ch in letters:
                letters[ch] += 1
            else:
                letters[ch] = 1

        ch = source.read(1)

    source.close()

    target = open(file_name + ".hist", "wt", encoding="utf-8")

    for letter, counter in sorted(letters.items(), key=lambda item: item[1], reverse=True):
        target.write(letter + " -> " + str(counter) + "\n")

    target.close()

    print("Istogramma salvato in:", file_name + ".hist")

except IOError as e:
    print("Errore di I/O:", strerror(e.errno))
