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

如何在不使用Counter的情况下统计CSV文件中单词的出现次数?

解决CSV单词计数问题

你的代码主要有两个问题:

  • csv.reader 读取的每一行是一个列表,你直接把整个列表作为字典的键,这显然不对,应该遍历列表里的每个单词
  • 原始CSV里的单词前后带有空格(比如 ' red'),如果不去除会导致同一个单词被当成不同条目统计

修正后的代码如下:

import csv

with open('afile.csv', 'r') as csvfile:
    word_count_dict = {}
    # 遍历csv文件的每一行
    for row in csv.reader(csvfile, delimiter=','):
        # 遍历当前行里的每个单词
        for word in row:
            # 去除单词前后的空白字符(空格、换行等)
            cleaned_word = word.strip()
            # 跳过空字符串(比如行尾可能出现的空值)
            if not cleaned_word:
                continue
            # 统计计数
            if cleaned_word in word_count_dict:
                word_count_dict[cleaned_word] += 1
            else:
                word_count_dict[cleaned_word] = 1

# 按照要求的格式输出结果
result = "、".join([f"{word} {count}" for word, count in word_count_dict.items()])
print(result)

测试你给出的输入内容:

house, red, knife, red, car, house, Red

运行代码后会输出:
house 2、red 2、knife 1、car 1、Red 1

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:45:34