首页 > 解决方案 > 字符串中第一个字母的单词计数器不起作用

问题描述

我试图让 Python 中的计数器按第一个字母计算单词。我可以让它计算所有内容,包括空格。

例如,在下面的代码中,以 's' 开头的单词数为 4。我知道这一点,但我的程序给我的 's' 为 10,即字符串中的每个 's'。我怎样才能让它只使用单词中的第一个字母?

from collections import Counter
my_str = "When I pronounce the word Future,\n the first syllable already belongs to the past.\n\n When I pronounce the word Silence,\n I destroy it.\n\n When I pronounce the word Nothing,\n I make something no nonbeing can hold.\n\n Wislawa Szymborska"
my_count = Counter(my_str.lower())
for word in [my_str]:
    my_count[word[0].lower()]+=1
print(my_count)

我的输出是:

Counter({' ': 37, 'e': 21, 'n': 19, 'o': 18, 't': 13, 'i': 12, 'h': 11, 'r': 11, 's': 10, 'w': 9, '\n': 9, 'a': 9, 'l': 8, 'd': 6, 'u': 5, 'c': 5, 'p': 4, 'y': 4, 'b': 4, 'g': 4, ',': 3, '.': 3, 'm': 3, 'f': 2, 'k': 2, 'z': 1})

标签: pythonstringcounter

解决方案


尝试这个:

from collections import Counter
from operator import itemgetter
my_str = "When I pronounce the word Future,\n the first syllable already belongs to the past.\n\n When I pronounce the word Silence,\n I destroy it.\n\n When I pronounce the word Nothing,\n I make something no nonbeing can hold.\n\n Wislawa Szymborska"
my_count = Counter(map(itemgetter(0), my_str.lower().split()))
print(my_count)

输出:

Counter({'w': 7, 'i': 6, 't': 6, 'p': 4, 's': 4, 'n': 3, 'f': 2, 'a': 1, 'b': 1, 'd': 1, 'm': 1, 'c': 1, 'h': 1})

推荐阅读