[英]Comparing two csv files using Python and find similar values in two file and save the similar values in another file as matching values
[英]How to find similar unique lines in two csv files using Python
我想计算两个csv(制表符分隔)文件中相似和相异条目的数量。
我一直在尝试使用python difflib来完成此任务。 以下是简化版本的两个输入文件的外观。 他们很大,有很多专栏。
文件A
ABC1 ABC2 SYMBOL EXCHANGE NAME ABC2 ABC3
234 f24 AAPL NYSE APPLE Inc.
23f3 ef23 ab3c jjm Google
sf2d df23 xyz tsx YourCompany
文件B
Exchange Symbol Name
Tok aapl Apple Jap.
NYSE QUAL Qualcom inc.
NYSE GOOG Google
查找相似性的规则:
ABC1,ABC2列仅用于演示目的,比较条目时请忽略它们。
原因是,我不能仅检查名称,因为大多数公司名称在不同的交易所具有不同的前缀/后缀,或者使用不同的语言。 但是交换和符号仅在这两个文件中是英文的。
上面示例的输出示例:
FileA and FileB has 2 number of common companies.
FileA has 1 number of companies which are not in FileB
FileB has 1 number of companies which are not in FileA
我是python的新手,到目前为止,我可以使用diff代码,但是还有很长的路要走。 想把这个问题放在这里。
import difflib
diff = difflib.ndiff(open("fileA").readlines(), open("fileB").readlines())
try:
while 1:
print diff.next(),
except:
pass
我想说的是,您需要的是每个文件一个字典,将公司名称映射到(交换,股票报价)元组。
通用元素和文件1特有的元素:
common_elements = {}
unique_to_file_1 = {}
for key, value in file1_dict.iteritems():
if key in file2_dict.keys() or value in file2_dict.values():
common_elements[key] = value
else:
unique_to_file_1[key] = value
文件2特有的元素:
unique_to_file_2 = {}
for key, value in file2_dict.iteritems():
if key not in common_elements.keys() and value not in common_elements.values():
unique_to_file_2[key] = value
我相信您确实知道如何从CSV文件创建这两个字典。
如果不知道数据是否包含重复项以及如何处理重复项,就很难回答。
集合操作非常快,因此我建议将一个文件解析为两个集合,然后遍历另一文件中的行以实现比较标准。
import csv
alist, blist = [], []
with open("fileA.tsv", "rb") as fileA:
reader = csv.reader(fileA, delimiter='\t')
for row in reader:
alist.append(row)
with open("fileB.tsv", "rb") as fileB:
reader = csv.reader(fileB, delimiter='\t')
for row in reader:
blist.append(row)
se_set_a = set([(row[2], row[3]) for row in alist])
name_set_a = set([row[4].strip() for row in alist])
symbol_exchange_matches = []
name_matches = []
for row in blist:
if (row[1], row[0]) in se_set_a:
symbol_exchange_matches.append((row[1], row[0]))
elif row[2].strip() in name_set_a:
name_matches.append(row[2])
matches = symbol_exchange_matches + name_matches
print "FileA and FileB have %i number of common companies." % (len(set(matches)),)
使用您的示例数据,我只找到一家普通公司:名称为“ Google”。 苹果不符合您的标准。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.