mthe25 mthe25 - 5 months ago 8
Python Question

Python basic program to count the letters in a file

I'm writing a program in Python for an online class in order to find the frequency of letters in a file. Thing is I keep getting spaces included in the final result too. How can I omit them? Here's my code:

import string
name = raw_input('Enter a file name: ')
fhandle = open(name)
counts = dict()
for line in fhandle:
line = line.strip()
line = line.translate(None,string.punctuation)
line = line.lower()
letters = list(line)
for letter in letters:
counts[letter]=counts.get(letter,0)+1
lst = list()
for letter,count in counts.items():
lst.append((count,letter))
lst.sort(reverse=True)
for count,letter in lst:
print count,letter

Answer

string.punctuation contains !"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ and no whitespace characters.

You should change your call to translate() to the following:

line.translate(None,string.punctuation+string.whitespace+string.digits)

Type help(string) in the python interpreter for more information.