You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 15:21:03