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?
JavaScript
x
15
15
1
import string
2
def LetterCount(str):
3
str= str.lower().strip()
4
str = str.strip(string.punctuation)
5
list1=list(str)
6
lcDict= {}
7
for l in list1:
8
if l in lcDict:
9
lcDict[l] +=1
10
else:
11
lcDict[l]= 1
12
print lcDict
13
14
LetterCount("Abracadabra, Monsignor")
15
Advertisement
Answer
You can also check if l is an alphabetic character (if l.isalpha()
)
Example:
JavaScript
1
16
16
1
import string
2
def LetterCount(str):
3
str= str.lower().strip()
4
str = str.strip(string.punctuation)
5
list1=list(str)
6
lcDict= {}
7
for l in list1:
8
if l.isalpha():
9
if l in lcDict:
10
lcDict[l] +=1
11
else:
12
lcDict[l]= 1
13
print lcDict
14
15
LetterCount("Abracadabra, Monsignor")
16