无法将单词的第一个字母与 A-Z 字母表进行比较

Can't get counter to compare first letter of word against A-Z alphabet

我要做的是将每个单词的首字母与 小写字母 a-z 并打印(类似于 word_frequency)多少 一个单词以字母表中的每个字母开头的次数 (比如这个)

a = 0 b = 2, c = 0, d = 2 ------------ y = 1, z = 0

但我目前无法找到通过 Counter 执行此操作的方法,也无法找到对我(初学者)有用的方法。我的想法是

    for w in word_count:
        l_freq = []
        l_freq.append(w[0])

然后将计数器与它进行比较?但不确定如何与整个字母表进行比较,而不仅仅是字符串中的字母?

还有,请问有什么方法可以打印频率清洁器吗?没有显示计数器和括号?

from collections import Counter

def function():
    string = "This is a string written in python."
    word_count = string.split()

    char_count = 0

    for char in string:
        if char != " " and char != ".":
            char_count += 1

    word_freq = Counter(word_count)

    print "Word count:  " + str(len(word_count))
    print "Average length of word: " + str(char_count / len(word_count))
    print ""
    print "Word frequency: "
    print word_freq

假设我们有这样的测试数据:

In [1]: test_data = '''
   ...: hello
   ...: hi
   ...: goodbye
   ...: bye
   ...: Bye!
   ...: lol
   ...: lmao
   ...: rofl
   ...: '''

要计算每个单词的第一个字母,您可以这样做:

counter = Counter(w[0] for w in test_data.split())

你基本上就是这样做的。要获得我 认为 你想要的预期输出,你只需要将每个小写字母与其计数相关联,就像这样(import string 如果你还没有):

for letter in string.ascii_lowercase:
    print letter, '=', counter[letter]

我展示的测试数据给你:

a = 0
b = 1
c = 0
d = 0
e = 0
f = 0
g = 1
h = 2
i = 0
j = 0
k = 0
l = 2
m = 0
n = 0
o = 0
p = 0
q = 0
r = 1
s = 0
t = 0
u = 0
v = 0
w = 0
x = 0
y = 0
z = 0