[英]Import Mongodb to CSV - removing duplicates
我将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文档具有相同的文本),我想保持第一个实例(关于时间)完好无损。 我导入时是否可以删除这些欺骗?
谢谢你的帮助!
我会使用一个集来存储数据的哈希值,并检查重复项。 像这样的东西:
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'))
值得注意的是,您可以直接使用文本字段,但对于存储仅哈希的较大文本字段,内存效率要高得多。
您只需要维护一个地图(字典)来维护(文本,时间戳)对。 “文本”是关键,因此不会有任何重复。 我将假设读取顺序不能保证首先返回最旧的时间戳。 在这种情况下,你必须进行2次传球 - 一次用于阅读,之后一次用于写作。
textmap = {} def insert(text, ts): global textmap if text in textmap: textmap[text] = min(ts, textmap[text]) else: textmap[text] = ts for r in db.hello.find(fields=['text', 'timestamp']): insert(r['text'], r['timestamp']) for text in textmap: print >>fp, text, textmap[text] # with whatever format desired.
最后,您还可以轻松地将字典转换为元组列表,以防您希望在打印前使用时间戳对结果进行排序。
(请参阅按值排序Python字典 )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.