0

i need to write a function which receives a long string, and puts into a dictionary each letter, and it's it's appearance frequency in the string. iv'e written the next function, but the problem it doesn't ignore whitespaces, numbers etc.. iv'e been asked to use the function symbol in string.ascii_lowercase, but iv'e no idea how to do it. this is my code:

def calc_freq(txt):
   dic={}
   for letter in range(len(txt)):
           if dic.has_key(txt[letter])==True:
                dic[txt[letter]] += 1
           else:
            dic[txt[letter]] = 1
   return dic

thanks for any help.

Dmitry B.
  • 9,107
  • 3
  • 43
  • 64
Orr
  • 57
  • 1
  • 8

2 Answers2

0
import string

s = 'oasndoasndoansdakls'
count = []
dictionary = {}

for x in set(s):
     if x in string.ascii_lowercase:
          dictionary[x] = s.count(x)

print (dictionary)

this will create a dictionary of the charactors and their counts, and only include them if they are in the string.ascii_lowercase list.


Here is how to use it in your code:

import string

def calc_freq(txt):
     dic={}
     for letter in txt:
          if letter in string.ascii_lowercase:
               if letter in dic:
                    dic[letter] += 1
               else:
                    dic[letter] = 1
     return dic

you just needed to add an if statment before you add the letter to the dictionary or increase its count.

I also removed the letter in range(txt) and txt[letter], you can access each charactor directly in python, because a string is an iterable and can be treated similar to a list.

Serdalis
  • 10,296
  • 2
  • 38
  • 58
  • @Orr added, I made it a bit easier to read for you, but if you want your original code, just replace what I changed. – Serdalis Dec 02 '11 at 01:55
  • what is the error? what are you passing it? It's working perfetly in my test, can I please have an example of input? – Serdalis Dec 02 '11 at 02:00
  • Traceback (most recent call last): File "", line 1, in calc_freq('zoobi') File "", line 4, in calc_freq if letter in string.ascii_lowercase: NameError: global name 'string' is not defined – Orr Dec 02 '11 at 02:02
  • you need to add `import string` to the top of your python file to access the lower_case list. – Serdalis Dec 02 '11 at 02:09
0

just for fun:

s = 'Type "help", "copyright", "credits" or "license" for more information.'
print dict(filter(lambda i: str.isalnum(i[0]), set(zip(a,map(a.count,a)))))

{'a': 1, 'c': 3, 'e': 6, 'd': 1, 'g': 1, 'f': 2, 'i': 5, 'h': 2, 'm': 2, 'l': 2, 'o': 6, 'n': 3, 'p': 3, 's': 2, 'r': 6, 't': 3, 'y': 2, 'T': 1}

Dmitry B.
  • 9,107
  • 3
  • 43
  • 64