首页 > 解决方案 > Python模糊匹配

问题描述

我有一个包含一百万行的数据库,我想将文本字段与 Excel 电子表格进行匹配,但是完全匹配的很少。因此,我创建了一个单词列表,其排名基于该单词的流行程度,即越独特,得分越高,匹配的可能性就越大。这运作良好且符合预期。但是,它很慢,因为我通过 SQL 游标循环电子表格,然后通过单词列表。

关于如何改进代码甚至给出类似答案的不同方法的任何建议?

wb = xl.load_workbook(in_file, data_only=True)
sh = wb['Sheet1']
max_row = sh.max_row + 1
max_col = sh.max_column + 1
with open(out_file, 'w', newline='') as file:
    writer = csv.writer(file)
    for xl_row in range(2, max_row):
        matched = []
        var = sh.cell(row=xl_row, column=1).value
        count = 0
        cursor.execute(sql)
        for sql_row in cursor:
            count += 1
            r = 0
            for word in word_list:
                if word[0] in var.upper() and word[0] in sql_row[1].upper():
                    r += word[1]
            if r > 0:
                matched.append([var, sql_row[0], sql_row[1], r])
                sys.stdout.write('\r' + str(count))
                sys.stdout.flush()

        matched.sort(key=lambda x: x[3], reverse=True)
        max_rtn = 0
        for match in matched:
            max_rtn += 1
            if max_rtn <= 5:
                print(match)
                writer.writerow(match)

示例数据:

word_list =[['Inc.', 3], ['Incorporated', 3], [Inc, 3], ['Group', 50], ['Orange', 215], ['Apple', 344]

data_set_1 = ['Apple Inc.', 'Orange Group']

data_set_2 = ['The Apple Group', 'Apple Inc', 'Orange Inc.', 'Orange']

在上面的示例中,“The Apple Group”匹配相同数量的单词,并且可能会得到与数据集 1 中的两个元素相似的 Levenshtein (fuzzywuzzy) 结果。但由于 Apple 具有更高的重要性,它将匹配到“Apple Inc.”。 ' 而不是“橙色集团”。数据集 1 是官方名称,数据集 2 是输入的更多人类数据。

标签: python

解决方案


推荐阅读