-2

Hello I am new to programming, and I need some help improving this code. I need to count how many times each letter of the alphabet occurs in the file and ignore the case of the letter; an 'A' and an 'a' are both counted as 'A'. The output needs to look like this something like this:

>A 20
>B 3
>C 5

This what I have so far:

file = open("LETTERCOUNT.txt", "w")
file.write("My name is Alexis Bernal, yet some people call me Lexi. I am currently eighteen years old. I really enjoy snowboarding, working out, hanging out with friends and trying new food. My favorite color is burgundy and my favorite animal is a giraffe. ")
import string
text = open('LETTERCOUNT.txt').read()
text = filter(lambda x: x in string.letters, text.lower())
for letter, repetitions in file:
    print (letter, repetitions)
kj007
  • 6,073
  • 4
  • 29
  • 47
  • 3
    Possible duplicate of [Count frequency of words in a list and sort by frequency](https://stackoverflow.com/questions/20510768/count-frequency-of-words-in-a-list-and-sort-by-frequency) – UltraInstinct Oct 28 '18 at 21:25
  • 2
    Possible duplicate of [Count frequency of letters in a text file](https://stackoverflow.com/questions/12342207/count-frequency-of-letters-in-a-text-file) – jainashish Oct 28 '18 at 22:06

1 Answers1

1

Use Counter

from collections import Counter

text = open('LETTERCOUNT.txt').read()
your_counts = Counter(text.upper())

your_counts will be a Counter object like this, you can call dict(your_counts) to turn it into a dictionary:

     'A': 2865,
     'B': 2751,
     'C': 2871,
     'D': 3013,
     'E': 3371,
     'F': 2737,
     'G': 2667,
     'H': 2835,
     'I': 2896,
     'J': 2624,
     'K': 2511,
     'L': 2794,
     'M': 2765,
     'N': 3091,
     'O': 3003,
     'P': 2951,
     'Q': 2751,
     'R': 2897,
     'S': 2811,
     'T': 3289,
     'U': 2953,
     'V': 2924,
     'W': 2634,
     'X': 2733,
     'Y': 2707,
     'Z': 2851,
Rocky Li
  • 5,641
  • 2
  • 17
  • 33