python - 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 是输入的更多人类数据。
解决方案
推荐阅读
- javascript - 元素在范围内向下滚动时显示
- codenameone - 代号一 电子邮件验证
- c++ - 我写了一个函数来删除循环链接列表中的第一个节点,但输出显示无限次“55 44 33 22 11 99”,那我该如何解决?
- java - Jackson:如何在 JSON 序列化中包含空值属性
- spring - Java Spring Swagger 不同的 API 文档
- wordpress - 仅显示图像 - 在 Wordpress 中不显示其他页面内容
- java - JPA嵌套事务在运行时异常后全部提交/回滚
- apache-spark - 从 pyspark 写入 cosmosdb 永远不会永远运行/永远不会成功也不会失败
- javascript - 输入数字 - 最大约束验证不起作用
- jboss7.x - 将 SameSite 属性添加到 JBoss AS7.1 应用程序