如何使用Power Query对比两列地址并返回三类匹配结果的M代码
Power Query 地址相似度匹配实现方案
可以实现,核心通过**编辑距离算法(Levenshtein距离)**判断文本相似度,结合包含关系覆盖拼写近似、部分匹配的场景。
实现步骤
- 首先在Power Query编辑器中新建自定义函数,用于计算两个文本的编辑距离(数值越小说明相似度越高),函数代码如下:
let LevenshteinDistance = (s as text, t as text) as number => let // 统一转为小写避免大小写干扰 sLower = Text.Lower(s), tLower = Text.Lower(t), // 构建距离矩阵 sc = Text.Length(sLower), tc = Text.Length(tLower), mat = List.Generate( () => [i=0, j=0, d=if i=0 then j else if j=0 then i else 0], (x) => x[i] <= sc, (x) => if x[j] = tc then [i=x[i]+1, j=0, d=if x[i]+1 <= sc then 0 else 0] else [i=x[i], j=x[j]+1, d=0], (x) => if x[i] = 0 then x[j] else if x[j] = 0 then x[i] else let cost = if Text.At(sLower, x[i]-1) = Text.At(tLower, x[j]-1) then 0 else 1, d1 = mat{(x[i]-1)*tc + x[j]}[d] + 1, d2 = mat{x[i]*tc + (x[j]-1)}[d] + 1, d3 = mat{(x[i]-1)*tc + (x[j]-1)}[d] + cost in List.Min({d1, d2, d3}) ) in mat{sc*tc + tc -1}[d] in LevenshteinDistance
将该函数命名为fn_LevenshteinDistance保存。
- 新建自定义列「Type of Match」,使用以下M代码逻辑:
let // 预处理:统一大小写、去除多余空格 addr1 = Text.Trim(Text.Lower([Addr1])), officeAddr = Text.Trim(Text.Lower([Office Address 1])), // 计算编辑距离和相似度阈值,可根据业务调整,这里按地址长度动态计算阈值 maxLen = List.Max({Text.Length(addr1), Text.Length(officeAddr)}), distance = fn_LevenshteinDistance(addr1, officeAddr), similarity = 1 - distance / maxLen in if addr1 = officeAddr then "完全匹配" else if Text.Contains(addr1, officeAddr) or Text.Contains(officeAddr, addr1) or similarity >= 0.8 then "部分匹配" else "无匹配"
参数调整说明
- 相似度阈值
0.8可根据实际业务场景调整,阈值越高匹配要求越严格 - 如需提升匹配准确率,可在预处理步骤加入去除标点、统一地址后缀(如Rd、Road统一替换为对应标准表述)的逻辑。
内容的提问来源于stack exchange,提问作者Jess
相关产品推荐
相关产品推荐

