'how to only get the alphabet letter from a string in python [closed]
I'm trying to create a program that takes in text from a file and outputs the frequency of each letter. The output also shows the frequency of '.' but I only want to output the frequency of letters. I'm trying to use isalpha() but I'm not sure where to put it. This is my code so far:
def count(str):
d = dict()
word = str.lower()
for i in word:
for j in i:
if j in d:
d[j] = d[j] + 1
else:
d[j] = 1
return d
print(count("Once upon a time there lived a princess who was too beautiful and kind to her subjects. The poets and artists were all in praise of her beauty and their works were inspired by her. Once a charming prince from another kingdom came to meet the princess and soon they became friends and slowly they fell in love"))
I tried putting isalpha() here:
for i in word.isalpha():
but it just gives me an error.
Solution 1:[1]
from string import ascii_lowercase as alphabet
# or simply declare: alphabet = 'abcdefghijklmnopqrstuvwxyz'
def letter_frequency(text):
frequency = {letter:0 for letter in alphabet}
for character in text.lower():
try:
frequency[character] += 1
except KeyError:
pass
return frequency
Solution 2:[2]
import string
alphabet_string = string.ascii_lowercase
alphabet_list = list(alphabet_string)
letter_count = {}
string = (
"Once upon a time there lived a princess who was too beautiful and"
"kind to her subjects.The poets and artists were all in praise of"
"her beauty and their works were inspired"
)
for char in alphabet_list:
letter_count[char] = 0
for char in string:
if char in alphabet_list:
letter_count[char] += 1
print (letter_count)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Michael Ekoka |
Solution 2 |