3

我想这对于一个体面的 Python 开发人员来说是一件容易的事——我还在学习!给定一个包含重复电子邮件的 csv,我想迭代并写出重复电子邮件的数量,例如:

文件.csv

COLUMN 0
some@email.com
some@email.com
another@address.com
example@email.com

输出文件.csv

COLUMN 0                 COLUMN 1
some@email.com           2
another@address.com      1
example@email.com        1

到目前为止,我可以删除重复项

import csv

f = csv.reader(open('infile.csv','rb'))
writer = csv.writer(open('outfile.csv','wb'))
emails = set()


for row in f:
    if row[0] not in emails:
        writer.writerow(row)
        emails.add( row[0] )

但我无法将计数写入新列。

4

3 回答 3

4

在 Python2.6使用defaultdictwhich

from collections import defaultdict

# count all the emails before we write anything out
emails = defaultdict(int)
for row in f:
    emails[row[0]] += 1

# now write the file
for row in email.items():
    writer.writerow(row)
于 2012-08-28T02:07:47.480 回答
3

试试柜台。它专为以下用途而设计:

from collections import Counter

emails=Counter()
for row in f:
    emails+=Counter([row[0]])

印刷:

Counter({'some@email.com': 2, 'another@address.com': 1, 'example@email.com': 1, 'COLUMN 0': 1})

从计数器获取任何其他数据结构很容易:

print set(emails.elements())
# set(['another@address.com', 'COLUMN 0', 'example@email.com', 'some@email.com']) 

请注意,我没有跳过标题或写出 csv - 这很容易做到。

于 2012-08-28T01:24:43.993 回答
1

对于 Python 2.6,您可以尝试类似鸽巢排序的方法:http: //en.m.wikipedia.org/wiki/Pigeonhole_sort

它实际上是为这种确切的问题而设计的。

For actual setup, use a dictionary to hold the data and then iterate over it instead of trying to write the info out as you go.

于 2012-08-28T02:08:06.137 回答