计数CSV中特定单词出现的Python算法 [英] Python algorithm of counting occurrence of specific word in csv

查看:62
本文介绍了计数CSV中特定单词出现的Python算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始学习python.我很好奇,除了简单地使用for循环逐行阅读之外,还有什么方法可以有效地计算CSV文件中特定单词的出现.

I've just started to learn python. I'm curious about what are the efficient ways to count the occurrence of a specific word in a CSV file, other than simply use for loop to go through line by line and read.

更具体地说,假设我有一个CSV文件,其中包含两列名称"和成绩",其中包含数百万条记录.

To be more specific, let's say I have a CSV file contain two columns, "Name" and "Grade", with millions of records.

如何计算等级"下"A"的出现?

How would one count the occurrence of "A" under "Grade"?

Python代码示例将不胜感激!

Python code samples would be greatly appreciated!

推荐答案

使用 csv 的基本示例代码> collections.Counter (来自标准Python libraly的Python 2.7 +):

Basic example, with using csv and collections.Counter (Python 2.7+) from standard Python libraly:

import csv
import collections

grades = collections.Counter()
with open('file.csv') as input_file:
    for row in csv.reader(input_file, delimiter=';'):
        grades[row[1]] += 1

print 'Number of A grades: %s' % grades['A']
print grades.most_common()

输出(对于小型数据集):

Output (for small dataset):

Number of A grades: 2055
[('A', 2055), ('B', 2034), ('D', 1995), ('E', 1977), ('C', 1939)]

这篇关于计数CSV中特定单词出现的Python算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆