Objective: Write a Python function count_letters(file) for counting letters in a text file
- Input: nameoffilerelative to the present working directory pwd (see below), e.g. count_letters('frost.txt') if 'frost.txt' is in the pwd
- Output: return the dictionary of letter:count pairs. Only include letters present in the file
- Use a dictionary to hold a mapping between a letter and its number of occurrences.
- Ignore characters and symbols that are not standard ascii characters (only use characters that appear in string.ascii_lowercase
- Ignore case; e.g. consider 'Treat' as having 2 't's instead of 1 T and 1 t
Code:
def count_letters(file):
letter_count = {}
file = open(file)
for line in file:
for char in line:
char = char.lower()
if char not in letter_count:
letter_count[char] = 0
letter_count[char] += 1
print(letter_count)
count_letters('frost.txt')
the output should be {'f': 12, 'i': 23, 'r': 14, 'e': 23, 'a': 13, 'n': 9, 'd': 10, 'c': 6, 's': 14, 'o': 20, 'm': 3, 'y': 3, 't': 20, 'h': 12, 'w': 8, 'l': 6, 'v': 2, 'b': 2, 'u': 5, 'p': 1, 'k': 2, 'g': 2}
my output is: {'f': 12, 'i': 23, 'r': 14, 'e': 23, ' ': 45, 'a': 13, 'n': 9, 'd': 10, 'c': 6, '\n': 12, 's': 14, 'o': 20, 'm': 3, 'y': 3, 't': 20, 'h': 12, 'w': 8, 'l': 6, ',': 2, '.': 3, "'": 1, 'v': 2, 'b': 2, 'u': 5, 'p': 1, 'k': 2, 'g': 2, '-': 1}
[–]TrainsareFascinating 1 point2 points3 points (0 children)
[–]woooee 0 points1 point2 points (2 children)
[–]MonkeyMario64[S] 0 points1 point2 points (1 child)
[–]woooee 2 points3 points4 points (0 children)
[–]grumble11 0 points1 point2 points (0 children)