你好,我是编程的新手,我需要一些帮助来改进此代码。我需要计算文件中每个字母的出现次数,并忽略字母的大小写; 'A'
和'a'
都计为'A'
。输出需要看起来像这样:
>A 20
>B 3
>C 5
这是我到目前为止所拥有的:
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)
答案 0 :(得分:1)
使用Counter
from collections import Counter
text = open('LETTERCOUNT.txt').read()
your_counts = Counter(text.upper())
your_counts
将是一个Counter对象,您可以调用dict(your_counts)
将其变成字典:
'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,