模糊比较两列

Fuzzy compare two column

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

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

如何针对文件 2 中的所有行对文件 1 中的每一行进行模糊查找?

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: list index out of range

知道如何使列表在范围内并且代码有效吗?

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()

我的猜测是,您可能想将 row.split() 更改为 row.split(','),但如果没有看到输入文件以及错误的确切回溯就无法确定。

下面的代码将起作用。确保安装了最新的 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()