开发者

Letter Count Dictionary

My homework problem is to write a Python function called LetterCount() which takes a string as an argument and returns a dictionary of letter counts. However, my code includes white space and commas as a part of the dictionary which i don't want. Can you please help me out. How do i remove the white space from my list? Here is my code?

开发者_如何学JAVA
import string
def LetterCount(str):
    str= str.lower().strip()
    str = str.strip(string.punctuation)
    list1=list(str)
    lcDict= {}
    for l in list1:
        if l in lcDict:
            lcDict[l] +=1
        else:
            lcDict[l]= 1
    print lcDict

LetterCount("Abracadabra, Monsignor")


For the letter count, the best way is to use the dictionary.

s = "string is an immutable object"
def letter_count(s):
    d = {}
    for i in s:
        d[i] = d.get(i,0)+1
    return d

Output:

{'a': 2, ' ': 4, 'c': 1, 'b': 2, 'e': 2, 'g': 1, 'i': 3, 'j': 1, 'm': 2, 'l': 1, 'o': 1, 'n': 2, 's': 2, 'r': 1, 'u': 1, 't': 3}


You can also check if l is an alphabetic character (if l.isalpha())

Example:

   import string
    def LetterCount(str):
            str= str.lower().strip()
            str = str.strip(string.punctuation)
            list1=list(str)
            lcDict= {}
            for l in list1:
                    if l.isalpha():
                            if l in lcDict:
                                    lcDict[l] +=1
                            else:
                                    lcDict[l]= 1
            print lcDict

    LetterCount("Abracadabra, Monsignor")


Extending python - Letter Count Dict:

from collections import Counter

def LetterCount(text):
    return Counter(c for c in text.lower() if c.isalpha())


Before you assign the count in the else branch, you should check whether l is a letter. Only assign the count if it is a letter.


From python doc (note the leading and trailing aspect):

string.strip(s[, chars]) Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.

Changed in version 2.2.3: The chars parameter was added. The chars parameter cannot be passed in earlier 2.2 versions.

You should take a look at str.replace() and DefaultDict :)


You want str.translate instead of str.strip.


Another option is to remove all non-alphabetic characters from the string using filter():

filter(str.isalpha, "Abracadabra, Monsignor")
'AbracadabraMonsignor'

(Be careful using this in your code -- you shadowed the built-in str by a variable of the same name. Never call a variable str.)


I don't want to do your homework for you because I don't thik it will help you but I'll try to uide you in the right direction, try this out:

alphabet = map(chr, range(97, 123))

or

alphabet2 = list(string.lowercase)

alphabet and alphabet2 will contain all the lowercase letters in the alphabet in a list.

Thanks eumiro for the remainder!


def count(string):

    return {i: string.count(i) for i in string}  

Yet another way


This is what I came up with...

  string = 'hello'
  d = {}
  for letter in string:
      if letter not in d:
          d[letter] = 0
      d[letter] += 1
  return d

Returns

{'h': 1, 'e': 1, 'l': 2, 'o': 1}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜