我试图让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})
试试这个:
输出:
使用列表理解和
.split()
-相关问题 更多 >
编程相关推荐