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

Python词频统计函数异常:输入句子后统计字母而非单词

Python单词词频统计程序问题修正

问题根源

原代码存在两个核心问题:

  • 遍历字符串时直接迭代每个字符(for word in words),而非将句子分割为独立单词
  • 未处理大小写不敏感的统计要求,导致ZyBooks和zyBooks被视为不同条目

修正步骤

  1. 分割句子为单词:使用split()方法将输入字符串按空格分割成单词列表,默认会自动处理多个连续空格的情况
  2. 统一单词大小写:将每个单词转换为小写(或大写),确保大小写不同的同一单词被归为一类
  3. 正确统计词频:遍历分割后的单词列表,逐个更新字典中的频率计数(避免用count()方法反复遍历原字符串,提升效率)

修正后的完整代码

def word_frequencies(words):
    freq = {}
    # 分割句子为单词列表,转小写实现大小写不敏感统计
    word_list = [word.lower() for word in words.split()]
    for word in word_list:
        # 若单词已在字典中,计数+1;否则初始化为1
        if word in freq:
            freq[word] += 1
        else:
            freq[word] = 1
    return freq

# 主程序保持不变
if __name__ == '__main__':
    words = input("Enter a sentence: ")
    your_dictionary = word_frequencies(words)
    sorted_keys = sorted(your_dictionary.keys())
    for key in sorted_keys:
        print(key + ': ' + str(your_dictionary[key]))

测试结果

输入句子 ZyBooks now zyBooks later zyBooks forever,输出为:

forever: 1
later: 1
now: 1
zybooks: 3

内容的提问来源于stack exchange,提问作者1TimeCoder

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 02:05:34