Counting letters in a text file As a beginner Python programmer, I wrote a simple program that counts how many times each letter appears in a text file. It works fine, but I'd like to know if it's possible to improve it.

def count_letters(filename, case_sensitive=False):
    alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

    with open(filename, 'r') as f:
        text = f.read()

    if not case_sensitive:
        alphabet = alphabet[:26]
        text = text.lower()

    letter_count = {ltr: 0 for ltr in alphabet}

    for char in text:
        if char in alphabet:
            letter_count[char] += 1

    for key in sorted(letter_count):
        print(key, letter_count[key])

    print("total:", sum(letter_count.values()))
@flornquake points at the good direction (use string and collections.Counter) but I'd still modify some details:


alphabet = alphabet[:26] and text = text.lower(): My advice is not to override existing variables with new values, it makes code harder to understand. Use different names.
if char in alphabet: Make sure you perform inclusion predicates with hashes, sets or similar data structures, not lists/arrays. O(1) vs O(n).
Functions should return values (hopefully related with their name). Here it makes sense to return the counter.


I'd write:

import collections
import string

def count_letters(filename, case_sensitive=False):
    with open(filename, 'r') as f:
        original_text = f.read()
    if case_sensitive:
        alphabet = string.ascii_letters
        text = original_text
    else:
        alphabet = string.ascii_lowercase
        text = original_text.lower()
    alphabet_set = set(alphabet)
    counts = collections.Counter(c for c in text if c in alphabet_set)

    for letter in alphabet:
        print(letter, counts[letter])
    print("total:", sum(counts.values()))

    return counts