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)
修改说明:
- 标点处理:用
strip(punctuation)移除单词首尾的标点,确保fox.这类带标点的单词能被正确识别为fox。 - 大小写统一:通过
lower()将所有单词转为小写,让The和the被合并统计为同一个单词。
运行修改后的代码,统计Frog.txt就能得到the 4的正确结果。
内容的提问来源于stack exchange,提问作者ColeTrain50
相关产品推荐
相关产品推荐

