-1

I am writing a program that produce a frequency plot of the letters in a body of text. however, there is an error in my code that I can not spot it. any ideas?

def letter_count(word,freqs,pmarks):
for char in word:
    freqs[char]+=1
def letter_freq(fname):
fhand = open(fname)
freqs = dict()
alpha = list(string.uppercase[:26])
for let in alpha: freqs[let] = freqs.get(let,0)
for line in fhand:
    line = line.rstrip()
    words = line.split()
    pmarks = list(string.punctuation)
    words = [word.upper() for word in words]
    for word in words:
        letter_count(word,freqs,pmarks)                                                                                   
 fhand.close()

return freqs.values

  • 1
    Hey Alqosh. I guess you know that indents are important in python. Please use the correct indents on your code to run it or to make it understandable for further help :) – choli Dec 21 '16 at 06:57
  • indents are not the problem (my intents are correct in my python). i get this error message: KeyError: ' . ' i never seen it before – Alqosh Hazkeal Dec 21 '16 at 08:33
  • Well, to understand the correct indents would be helpful for everyone who wants to help as well. – choli Dec 21 '16 at 09:13
  • you are right. but as i said the problem is not with indents. i need to test if [char] in line 3 is punctuation mark or not, then update the freqs[char] – Alqosh Hazkeal Dec 21 '16 at 09:41

1 Answers1

0

You are calling

freqs[char]+=1

with char = '.' without having initialized a value freqs['.']=0

You should check before line 3, whether the key exists already, as you can do the +=1 operation only on existing keys of the dictionary.

So something like:

for char in word:
    if freqs.has_key(char):
        freqs[char]+=1

Python: how can I check if the key of an dictionary exists?

Community
  • 1
  • 1
choli
  • 312
  • 1
  • 4
  • 14