Christopher Flach Christopher Flach - 1 year ago 102
Python Question

Python Create Count of Letters from Text File

I'm trying to do a count of the letters only from a text file. I want to exclude any punctuation and spaces. Here's what I have so far. I've been searching for ways to do this, but I keep getting errors whenever I try to exclude certain characters. Any help is greatly appreciated.

#Read Text Files To Memory
with open("encryptedA.txt") as A:
AText =
with open("encryptedB.txt") as B:
BText =

#Create Dictionary Object
from collections import Counter
CountA = Counter(AText)
CountB = Counter(BText)

Answer Source

You are on the right track, but you want to filter the text-file based on characters that are alphabetic (using isalpha()) or alphanumeric (using isalnum()):

from collections import Counter
with open('data.txt') as f:
    print (Counter(c for c in if c.isalpha())) # or c.isalnum()

For my sample file, this prints:

Counter({'t': 3, 'o': 3, 'r': 3, 'y': 2, 's': 2, 'h': 2, 'p': 2, 'a': 2, 'g': 1, 'G': 1, 'H': 1, 'i': 1, 'e': 1, 'M': 1, 'S': 1})
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download