def get_word_frequencies(filename):
    freqs = {}
    for line in open(filename):
        for char in line.split():
            if char in freqs:
                freqs[char] += 1
            else:
                freqs[char] = 1
  return freqs


我从文本文件中拆分字符并找到其频率时遇到问题。我已经写了这段代码,但是只能找到单词。我想要A-Z词典中的字母。

最佳答案

您可以使用collections.Counterstring.ascii_letters来获取字母数。使用string.ascii_letters将只允许您计算字母,不包括标点符号等。

from collections import Counter
from string import ascii_letters

def get_word_frequencies(filename):
    with open(filename) as f:
        c = Counter(f.read())
    return {k:v for k,v in c.items() if k in ascii_letters}

c = get_word_frequencies('derp.py')

print(c)
# {'o': 12, 'h': 1, 'C': 2, 't': 16, 'i': 18, 'y': 1, 'u': 5, 'f': 11, 'p': 6,
# 'v': 2, 'c': 10, 'm': 7, 'n': 13, 'k': 3, 'd': 5, 'a': 6, 'q': 2, 'w': 3,
# 's': 10, 'g': 3, 'r': 19, 'l': 6, 'e': 25}

08-19 17:35