字符串中第一个字母的单词计数器不工作

2024-06-06 22:46:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让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})

Tags: the代码mycount字母counter计数器空间
2条回答

试试这个:

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})

使用列表理解和.split()-

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([i[0].lower() for i in my_str.split()])

print(my_count)

相关问题 更多 >