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

Python词频统计代码问题:无法合并大小写单词统计次数

问题解决:统一单词大小写并处理标点

你的代码目前会区分单词大小写,且未处理单词附带的标点,导致开头的The和小写the被算作不同单词,带标点的单词也会被单独统计。可以通过以下两处修改解决问题:

  • 将所有单词转换为小写,消除大小写差异
  • 去除单词首尾的标点符号,避免带标点的单词干扰统计

修改后的代码如下:

name = input('Enter a file name: ')
with open(name) as handle: 
    counts = dict()
    # 定义需要清理的标点符号,可按需补充
    punctuation = '''.,!?;:'"'''
    for line in handle :
        words = line.split()
        for word in words :
            # 先去除首尾标点,再转小写
            cleaned_word = word.strip(punctuation).lower()
            counts[cleaned_word] = counts.get(cleaned_word, 0) + 1
    
    bigcount = None
    bigword = None
    for word, count in counts.items() :
        if bigcount is None or count > bigcount:
            bigword = word
            bigcount = count
    
    print(bigword, bigcount)

修改说明:

  1. 标点处理:用strip(punctuation)移除单词首尾的标点,确保fox.这类带标点的单词能被正确识别为fox。
  2. 大小写统一:通过lower()将所有单词转为小写,让The和the被合并统计为同一个单词。

运行修改后的代码,统计Frog.txt就能得到the 4的正确结果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 11:54:51