我正在将数据从Mongo导入到CSV文件中。导入由每个JSON文档的“时间戳”和“文本”组成。
文档:
{
name: ...,
size: ...,
timestamp: ISODate("2013-01-09T21:04:12Z"),
data: { text:..., place:...},
other: ...
}
代码:
with open(output, 'w') as fp:
for r in db.hello.find(fields=['text', 'timestamp']):
print >>fp, '"%s","%s"' % (r['text'], r['timestamp'].strftime('%H:%M:%S'))
我想删除重复的(一些Mongo文档有相同的文本),我想保持第一个实例(关于时间)完好无损。是否可以在导入时删除这些重复项?
谢谢你的帮忙!
发布于 2013-01-11 02:26:05
我将使用一个集合来存储数据的散列,并检查重复项。如下所示:
import md5
hashes = set()
with open(output, 'w') as fp:
for r in db.hello.find(fields=['text', 'timestamp']):
digest = md5.new(r['text']).digest()
if digest in hashes:
# It's a duplicate!
continue
else:
hashes.add(digest)
print >>fp, '"%s","%s"' % (r['text'], r['timestamp'].strftime('%H:%M:%S'))
值得注意的是,您可以直接使用文本字段,但对于较大的文本字段,仅存储散列的内存效率要高得多。
https://stackoverflow.com/questions/14264575
复制相似问题