模糊比较两列

时间:2015-05-19 19:28:58

标签: python fuzzy-logic fuzzy-comparison fuzzywuzzy

我有一个包含搜索字词(数字和文字)的CSV文件,我想与其他字词(数字和文字)列表进行比较,以确定是否存在任何匹配或潜在匹配。然后我想将所有结果写入新的CSV进行人工审核。我正在使用fuzzywuzzy插件创建一个“得分”来确定这些术语之间的匹配程度。理想情况下,我可以过滤比率。

我当前的代码将文件行一对一比较,而不是将第一个文件中的一行与第二个文件中的所有行进行比较;这就是我需要的。

如何针对file2中的所有行对file1中的每一行进行模糊查找?

from fuzzywuzzy import fuzz
import csv
from itertools import zip_longest

f = open('FuzzyMatch2.csv', 'wt')
writer = csv.writer(f, lineterminator = '\n')


file1_loc = 'LookUp.csv'
file2_loc = 'Prod.csv'

file1 = csv.DictReader(open(file1_loc, 'r'), delimiter=',', quotechar='"')
file2 = csv.DictReader(open(file2_loc, 'r'), delimiter=',', quotechar='"')

for row in file1:
    for l1, l2 in zip_longest(file1, file2):
        if all((l1, l2)):
            partial_ratio = fuzz.token_sort_ratio(str(l1['SearchTerm']), str(l2['Description']))       

        a = [l1,l2,partial_ratio]
        writer.writerow(a)

f.close()

以下是上述代码的更清晰版本,但仍存在问题。代码给出了错误

  

IndexError:列表索引超出范围

知道如何让范围内的列表和代码有效吗?

from fuzzywuzzy import process
import csv

save_file = open('FuzzyResults.csv', 'wt')
writer = csv.writer(save_file, lineterminator = '\n')

def parse_csv(path):
    with open(path,'r') as f:
        for row in f:
            row = row.split()
            yield row


if __name__ == "__main__":
    ## Create lookup dictionary by parsing the products csv
    data = {}
    for row in parse_csv('Prod.csv'):
        data[row[0]] = row[1]

    ## For each row in the lookup compute the partial ratio
    for row in parse_csv("LookUp.csv"):

        for found, score in process.extract(row, data, limit=100):
            if score >= 10:
                print('%d%% partial match: "%s" with "%s" ' % (score, row, found))
                Digi_Results = [score, row, found]
                writer.writerow(Digi_Results)


save_file.close()

2 个答案:

答案 0 :(得分:1)

以下代码可行。确保安装了最新的FuzzyWuzzy - 最后更新28APR15。否则你会收到一个' unicode'错误。希望这有帮助!

from fuzzywuzzy import process
import csv

save_file = open('FuzzyResults3.csv', 'w')
writer = csv.writer(save_file, lineterminator = '\n')

def parse_csv(path):

    with open(path,'r') as f:
        reader = csv.reader(f, delimiter=',')
        for row in reader:
            yield row


if __name__ == "__main__":
    ## Create lookup dictionary by parsing the products csv
    data = {}
    for row in parse_csv('File1.csv'):
        data[row[0]] = row[1]

    ## For each row in the lookup compute the partial ratio
    for row in parse_csv("File2.csv"):
        #print(process.extract(row,data, limit = 100))
        for found, score, matchrow in process.extract(row, data, limit=100):
            if score >= 60:
                print('%d%% partial match: "%s" with "%s" ' % (score, row, found))
                Digi_Results = [score, row, found]
                writer.writerow(Digi_Results)


save_file.close()

答案 1 :(得分:0)

我的猜测是,您可能希望将row.split()更改为row.split(','),但无法在不查看输入文件的情况下确定,也可以确切地追溯错误。