Christopher Flach Christopher Flach - 1 month ago 6
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 = A.read()
with open("encryptedB.txt") as B:
BText = B.read()

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

Answer

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 f.read() 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})
Comments