所以我有两个我想要比较的CSV文件并获得类似项目的结果。 第一个文件hosts.csv如下所示:
Path Filename Size Signature
C:\ a.txt 14kb 012345
D:\ b.txt 99kb 678910
C:\ c.txt 44kb 111213
第二个文件masterlist.csv如下所示:
Filename Signature
b.txt 678910
x.txt 111213
b.txt 777777
c.txt 999999
正如您所看到的行不匹配,并且masterlist.csv始终大于hosts.csv文件。我想要搜索的唯一部分是Signature部分。我知道这看起来像是:
hosts[3] == masterlist[1]
我正在寻找一个能给我类似下面的解决方案(基本上是带有新RESULTS列的hosts.csv文件):
Path Filename Size Signature RESULTS
C:\ a.txt 14kb 012345 NOT FOUND in masterlist
D:\ b.txt 99kb 678910 FOUND in masterlist (row 1)
C:\ c.txt 44kb 111213 FOUND in masterlist (row 2)
我搜索了这些帖子,发现了类似于here的内容,但我不太明白,因为我还在学习python。
编辑使用Python 2.6
答案 0 :(得分:21)
srgerg的答案极其低效,因为它以二次方式运作;这是一个线性时间解决方案,使用Python 2.6兼容语法:
import csv
with open('masterlist.csv', 'rb') as master:
master_indices = dict((r[1], i) for i, r in enumerate(csv.reader(master)))
with open('hosts.csv', 'rb') as hosts:
with open('results.csv', 'wb') as results:
reader = csv.reader(hosts)
writer = csv.writer(results)
writer.writerow(next(reader, []) + ['RESULTS'])
for row in reader:
index = master_indices.get(row[3])
if index is not None:
message = 'FOUND in master list (row {})'.format(index)
else:
message = 'NOT FOUND in master list'
writer.writerow(row + [message])
这将生成一个字典,首先将masterlist.csv
的签名映射到行号。字典中的查找需要恒定时间,使第hosts.csv
行的第二个循环与masterlist.csv
中的行数无关。更不用说代码更简单了。
对于那些使用Python 3的人,上面只需要调整open()
调用以在文本模式下打开(从文件模式中删除b
),并且你想添加{{1因此CSV阅读器可以控制行分隔符。您可能希望声明显式使用的编码,而不是依赖于系统默认值(使用new line=''
)。可以使用字典理解(encoding=...
)构建master_indices
映射。
答案 1 :(得分:11)
修改:虽然我的解决方案正常运行,但请查看下面的Martijn答案,以获得更有效的解决方案。
您可以找到python CSV模块here的文档。
您正在寻找的是这样的:
import csv
f1 = file('hosts.csv', 'r')
f2 = file('masterlist.csv', 'r')
f3 = file('results.csv', 'w')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.writer(f3)
masterlist = list(c2)
for hosts_row in c1:
row = 1
found = False
for master_row in masterlist:
results_row = hosts_row
if hosts_row[3] == master_row[1]:
results_row.append('FOUND in master list (row ' + str(row) + ')')
found = True
break
row = row + 1
if not found:
results_row.append('NOT FOUND in master list')
c3.writerow(results_row)
f1.close()
f2.close()
f3.close()
答案 2 :(得分:4)
Python的CSV和集合模块,特别是OrderedDict,在这里非常有用。你想使用OrderedDict来保存键的顺序等等。你不必这样做,但它很有用!
import csv
from collections import OrderedDict
signature_row_map = OrderedDict()
with open('hosts.csv') as file_object:
for line in csv.DictReader(file_object, delimiter='\t'):
signature_row_map[line['Signature']] = {'line': line, 'found_at': None}
with open('masterlist.csv') as file_object:
for i, line in enumerate(csv.DictReader(file_object, delimiter='\t'), 1):
if line['Signature'] in signature_row_map:
signature_row_map[line['Signature']]['found_at'] = i
with open('newhosts.csv', 'w') as file_object:
fieldnames = ['Path', 'Filename', 'Size', 'Signature', 'RESULTS']
writer = csv.DictWriter(file_object, fieldnames, delimiter='\t')
writer.writer.writerow(fieldnames)
for signature_info in signature_row_map.itervalues():
result = '{0} FOUND in masterlist {1}'
# explicit check for sentinel
if signature_info['found_at'] is not None:
result = result.format('', '(row %s)' % signature_info['found_at'])
else:
result = result.format('NOT', '')
payload = signature_info['line']
payload['RESULTS'] = result
writer.writerow(payload)
以下是使用测试CSV文件的输出:
Path Filename Size Signature RESULTS
C:\ a.txt 14kb 012345 NOT FOUND in masterlist
D:\ b.txt 99kb 678910 FOUND in masterlist (row 1)
C:\ c.txt 44kb 111213 FOUND in masterlist (row 2)
请原谅错位,它们是分开的:)
答案 3 :(得分:0)
csv
模块在解析csv文件时非常方便。但只是为了好玩,我只是简单地在空格上分割输入来获取数据。
只需解析数据,为masterlist.csv中的数据构建dict
,其中签名为key,行号为value。现在,对于hosts.csv的每一行,我们只需查询dict
并查明masterlist.csv中是否存在相应的条目,如果存在,则查找该行。
#! /usr/bin/env python
def read_data(filename):
input_source=open(filename,'r')
input_source.readline()
return [line.split() for line in input_source]
if __name__=='__main__':
hosts=read_data('hosts.csv')
masterlist=read_data('masterlist.csv')
master=dict()
for index,data in enumerate(masterlist):
master[data[-1]]=index+1
for row in hosts:
try:
found="FOUND in masterlist (row %s)"%master[row[-1]]
except KeyError:
found="NOT FOUND in masterlist"
line=row+[found]
print "%s %s %s %s %s"%tuple(line)
答案 4 :(得分:-1)
我只是在Martijn Pieters代码中修复了一个小问题,以使其能够在Python 3中工作,并且在此代码中,我试图将file1 row[0]
中的第一列元素与第一列元素进行匹配在文件2 row[0]
中。
import csv
with open('file1.csv', 'rt', encoding='utf-8') as master:
master_indices = dict((r[0], i) for i, r in enumerate(csv.reader(master)))
with open('file2.csv', 'rt', encoding='utf-8') as hosts:
with open('result.csv', 'w') as results:
reader = csv.reader(hosts)
writer = csv.writer(results)
writer.writerow(next(reader, []) + ['RESULTS'])
for row in reader:
index = master_indices.get(row[0])
if index is not None:
message = 'FOUND in master list (row {})'.format(index)
writer.writerow(row + [message])
else:
message = 'NOT FOUND in master list'
writer.writerow(row + [message])
results.close()