首页 > 解决方案 > 比较两个python列表以发现差异并忽略拼写错误

问题描述

我有两张 Excel 表格,正在构建一个小程序来比较这些表格中的两列以找出差异。问题是,由于这些输入大部分是手动完成的,因此存在很多拼写错误,应该忽略。该程序应突出显示新的或已删除的数据。

我正在阅读模糊文本,我在网上找到了这段代码(链接),但它的输出只是生成了一个带有完全相同条目的 CSV(不是我想要的)。我仍然会在此处添加它,以便您知道我在说什么。

from __future__ import division
import numpy as np
import pandas as pd
from collections import Counter
import collections
from fuzzywuzzy import fuzz
import time
from two_lists_similarity import Calculate_Similarity as cs

#the first file
book_old = pd.read_excel(r' #Input file here', sheet_name = '#Sheet Name Here')
data_old = book_old.iloc[7:,2].tolist()
#Selecting the column i want to compare

#second file to compare with
book_new = pd.read_excel(r'#source here', sheet_name = '#Sheet name')
data_new = book_new.iloc[7:,2].tolist() #selecting col

inp_list = data_old
ref_list = data_new
#this is what i picked up online because i couldnt do myself
#the plan is to iterate the list and find entries that are different, ignore spellings
# Create an instance of the class. This is otherwise called as an object 
csObj = cs(inp_list,ref_list)
# csObj is now the object of Calculate Similarity class. 
csObj.fuzzy_match_output(output_csv_name = 'pkg_sim_test_vsc.csv', output_csv_path = r'#Output path')

标签: pythonpython-3.xlistfuzzy-comparison

解决方案


您需要的可能是一些计算两个字符串差异程度的函数。

事实证明,已经有一些算法可以做到这一点!查看Damerau–Levenshtein distance,这似乎是最接近您的用例的。来自维基百科:

通俗地说,两个单词之间的 Damerau-Levenshtein 距离是将一个单词变为另一个单词所需的最小操作数(包括单个字符的插入、删除或替换,或两个相邻字符的转置)。

但是,这只会发现简单的拼写错误并且容易出现误报,因此您可能希望将其与其他一些机制结合使用。

网络上有该算法的 Python 实现(参见此处此处)。

或者,随时查看其他一些算法,例如:


推荐阅读