Python使用Counter按单词首字母统计结果错误如何解决
代码修改方案
原代码问题分析
- 直接调用
Counter(my_str.lower())是对整个字符串的每一个字符做统计,所以会把空格、换行、标点、单词中间的字母全部纳入计数,不是你要的首字母统计逻辑 - 后续循环
for word in [my_str]:是把完整的长字符串当成唯一的元素遍历,完全没有拆分出独立单词,无法实现每个单词首字母的统计需求
修正后代码
from collections import Counter my_str = """When I pronounce the word Future, the first syllable already belongs to the past. When I pronounce the word Silence, I destroy it. When I pronounce the word Nothing, I make something no nonbeing can hold. Wislawa Szymborska""" # 拆分单词后提取清洗后的首字母 first_letters = [] for word in my_str.split(): # 去除单词前后附着的标点符号 cleaned_word = word.strip(',.!?') if cleaned_word: first_letters.append(cleaned_word[0].lower()) # 仅统计首字母频次 my_count = Counter(first_letters) print(my_count)
运行效果
修正后输出中s的计数为4,完全符合你的预期。如果需要同时保留全字符统计结果,可以单独声明另一个Counter对象做统计,不要和首字母统计的Counter混用即可。
内容的提问来源于stack exchange,提问作者SassyG
相关产品推荐
相关产品推荐

