我有两个文件要合并(left join),以标识从左文件返回的记录与右文件中匹配的行。在
匹配键基于定义邮政数据的列的选择。我正在研究定义匹配阈值的方法,并为重复管理的唯一地址分配一个唯一的密钥。这也叫做householding,它意味着新的匹配不会减少处理过程。在
真正的挑战是对非常大的文件高效地运行主匹配循环。在
这个设置可能是map/reduce的一个很好的候选者,但是我现在想探索自包含的(比如“不太天真”)解决方案。在
有什么想法吗?谢谢。在import csv
import StringIO
from fuzzywuzzy import fuzz
cols1 = [ 1 , 3 , 4]
f1 = '''x1,x2,x3,x4,x5
the,quick,brown,fox,jumps
over,the,lazy,dogs,back,
bla,bla,bla,bla,bla'''
cols2 = [ 2 , 3 , 4]
f2 = '''x1,x2,x3,x4,x5
the,fast,brown,fox,jumps
over,many,snoozing,dogs,back,
the,prompt,fuchsia,fox,jumps
over,the,lazy,dogs,back,
bl,the,bl,bl,fox'''
def standardize( x , selection , field_lengths=None ):
y = ','.join([ x[selection[i]] for i in range(len(selection)) ])
return y
f1 = StringIO.StringIO(f1)
f2 = StringIO.StringIO(f2)
reader1 = csv.reader( f1 )
reader2 = csv.reader( f2 )
keys2 = []
for row in reader2:
# standardize and load key
keys2.append( standardize( row , cols2 ) )
for row in reader1:
# standardize and compare
key1 = standardize( row , cols1 )
# ------------------------------------------------
matches = [ fuzz.ratio( key1 , k) for k in keys2 ]
# ------------------------------------------------
max_match = max( matches )
max_pos = [i for i, x in enumerate(matches) if x == max_match ][0]
print key1 , "-->" , keys2[max_pos] , ':' , max_match