BrainBank
AI 课堂/技能Machine Learning

模糊匹配算法

2026/8/3 17:29:23 · 更新于 2026/8/3 17:47:27 · 来源

AI 翻译于 2026/8/3 17:50:45 · 使用 Qwen3.6 35B (fast, default)

#skill#fuzzy-matching#edit-distance#levenshtein-distance#damerau-levenshtein#bitap-algorithm#n-gram#spell-checking#text-similarity#data-deduplication#python-implementations

模糊字符串匹配算法综合指南 —— 涵盖 Levenshtein、Damerau-Levenshtein、Bitap 和 n-gram —— 详解编辑距离度量如何实现近似模式匹配,并应用于拼写检查、去重处理、抄袭检测、生物信息学等多个领域。

模糊字符串匹配是一种寻找近似匹配字符串的技术。它被广泛应用于拼写检查器、记录去重、主数据管理、抄袭检测、生物信息与 DNA 测序、垃圾邮件过滤、内容搜索、相似度匹配等场景。

本文将介绍几种用于此类模糊字符串匹配的算法——Levenshtein、Damerau-Levenshtein、Bitapn-gram。详细的 Python 实现与代码可在 GitHub repoJupyter notebook 中找到。

(本内容曾作为 Women Who Code 数据科学会议于 2022 年 4 月进行分享。会议的录像已发布在 YouTube 上。)

模糊匹配简介

字符串匹配或模糊匹配是一种用于寻找与给定模式或字符串近似匹配的文本的方法。它基于某些参数来评估两条记录真正匹配的可能性或概率。在下方的示例中,算法尝试将 5 个不同的变体与给定的字符串‘Microsoft Corporation’进行匹配,并根据它们与真实值的接近程度对每个变体进行评分。

按回车键或点击以查看完整图片

字符串/模糊匹配的应用示例

使用的算法

最常用的模糊匹配算法涉及计算字符串之间的编辑距离指标。Edit distance metric量化了_通过将其中一个字符串转换为另一个所需的最少操作次数,来衡量两个字符串的相异程度_。一些著名的距离度量标准包括:

  • Levenshtein distance
  • Damerau–Levenshtein distance
  • Longest common subsequence
  • Hamming distance
  • Jaro distance

Bitap algorithm (shift-or, shift-and algorithm or Baeza-Yates–Gonnet algorithm) 用于判断给定文本中是否包含与给定模式“近似相等”的子串,同样利用了 Levenshtein 距离。它对相对较短的模式字符串非常高效。Bitap 算法是 Unix 系统中 agrep/grep 实用函数的核心。

n-gram 算法使用马尔可夫模型来预测文本序列中的下一个元素。n-gram 是以特定顺序排列的 n 个字符(单词、字母、符号等)的模式。在文本处理中,使用 n-grams 有助于捕捉与词序相关的信息。

Bitap 和 n-gram 算法的主要区别在于前者属于_在线(on-line)_方法,而后者属于_离线(off-line)_方法。在线算法无需索引即可进行搜索,因此在处理大规模数据时性能较低效。离线技术在搜索中引入索引机制,使搜索速度大幅提升,并广泛应用于文本处理领域。

其他常用的算法包括 Needleman–Wunsch 算法、Smith–Waterman 算法、BK Tree metric、Soundex 或 Metaphone(后者是一种语音算法)。

编辑距离指标——莱文斯坦距离与达梅劳-莱文斯坦距离

编辑距离metric(指标)用于衡量将其中一个词转换为另一个词所需的编辑操作次数。莱文斯坦距离是一种流行的计算编辑距离的方法。下图展示了莱文斯坦距离和达梅劳-莱文斯坦距离的工作原理以及两者之间的差异。

点击或按回车键全屏查看图片

莱文斯坦距离与达梅劳-莱文斯坦距离 点击或按回车键全屏查看图片

计算莱文斯坦距离与达梅劳-莱文斯坦距离 以下是该算法的数学原理说明。 点击或按回车键全屏查看图片

计算莱文斯坦距离背后的数学原理

莱文斯坦距离具有以下特性:

  • 当且仅当两个字符串相等时,其值为零。
  • 其值至少为两个字符串长度之差的绝对值。
  • 其值不超过较长字符串的长度。
  • 三角不等式:任意两个字符串之间的莱文斯坦距离不大于它们各自与第三个字符串的莱文斯坦距离之和。

Python 实现

点击或按回车键全屏查看图片

Bitap 算法

这是一种在线搜索方法(即无需索引的搜索),使用莱文斯坦距离来计算目标字符串与给定模式之间的近似匹配度。Bitap 算法对位掩码(bitmask,用于执行位运算的数据结构)进行位运算操作,速度极快。通过位掩码,多个位在单个位运算中可同时置为开或关,或在开和关之间翻转。该算法在短长度模式下表现最佳,这得益于其底层数据结构的支持。

在您的收件箱中获取 Madhurima Nath, PhD 的文章

注册 Medium 以免费获取该作者的更新。 订阅

记住我以便更快登录

_示例 1:
输入文本:womenwhocode,模式:code
输出:Pattern found at index: 8(在第 8 个索引处找到模式)

_示例 2:
输入文本:youareawesome,模式:youareamazing
输出:No Match(无匹配结果)

Python 实现

点击或按回车键全屏查看图片

这是我参考 GeekforGeeks 上的代码编写的 Bitap 搜索 Python 实现版本。 点击或按回车键全屏查看图片

这是我参考 GeekforGeeks 上的代码编写的 Bitap 搜索 Python 实现版本。

n-gram 算法

该算法以马尔可夫模型的形式预测文本序列中的下一个项目。它是一种离线搜索,即在索引上进行搜索,从而大幅提升了处理大数据时的计算效率。目前,n-gram 技术几乎被应用于所有的自然语言处理算法中。n-gram 是通过对字符串中连续出现的 n 个字符/词进行配对而生成的一组值。其目标是计算字符/词序列或句子的概率。 按回车键或点击查看全尺寸图片 n-gram 算法的数学原理 在本笔记本中,这些算法应用于一个简单的示例,以展示这些方法之间的相似之处与差异。

学习地图

Fuzzy Matching Algorithms — Learning Roadmap

Stage 1: Foundations

  • Understand why approximate string matching matters (exact match is often insufficient in real-world data)
  • Learn about edit distance metrics: Levenshtein, Damerau-Levenshtein, Hamming, Jaro-Winkler, longest common subsequence
  • Grasp the difference between on-line (Bitap) and off-line (n-gram) search strategies

Stage 2: Core Algorithms & Mathematics

  • Levenshtein Distance: Master dynamic programming approach — insertions, deletions, substitutions, with their cost matrix visualization
  • Damerau-Levenshtein: Learn the transposition operation added to Levenshtein and why it matters for human typos
  • Bitap (Shift-Or/Shift-And): Understand bitmask-based approximate matching for short patterns
  • n-gram Matching: Study Markov model foundations and how character/word-level n-grams capture positional information

Stage 3: Python Implementation

  • Implement each algorithm from scratch using matrices and bitwise operations
  • Use difflib.SequenceMatcher (built-in) for quick prototyping
  • Benchmark algorithms against each other on realistic data

Stage 4: Real-World Applications

  • Build spell checkers with edit-distance thresholds
  • Implement record de-duplication for master data management
  • Apply to plagiarism detection and similarity search pipelines
  • Explore bioinformatics applications (DNA sequence alignment variants like Needleman-Wunsch, Smith-Waterman)

动手实践——分步指南

  1. Set up a Python environment (Python 3.9+ with numpy) and create a project folder for fuzzy matching experiments.
  2. Run pip install numpy to get the array operations needed for matrix-based implementations.
  3. Study Levenshtein distance by manually filling in its cost matrix — given s1='kitten' and s2='sitting', trace how each insertion/deletion/substitution builds the DP table step by step.
  4. Write a Python function that implements Levenshtein distance from scratch using a 2D array: initialize a (m+1)x(n+1) matrix with row/column indices as base costs, then fill it iteratively comparing each character pair.
  5. Copy and run the Damerau-Levenshtein implementation that adds a transposition cost to the Levenshtein logic — test it on strings like 'cafe' vs 'cafe' (identical) and 'abx' vs 'axy'.
  6. Implement the Bitap (shift-or) algorithm using Python's built-in integers as bitmasks: for each character in your alphabet, precompute a bitmask; then use bitwise OR and AND operations to slide a window over the text.
  7. Build an n-gram splitter function that takes a string and integer n, then returns all overlapping n-character sequences (e.g., 'hello' with n=2 yields ['he','el','ll','lo']). Compute similarity by comparing two lists of n-grams using Jaccard or cosine similarity.
  8. Compare all four algorithms on the same test cases: misspelled company names, near-duplicate records, and short pattern searches — record execution time and accuracy for each.
  9. Pick one real-world scenario from spell checking, deduplication, or plagiarism detection and build a minimal pipeline using your favorite algorithm from Steps 3-6.

三大推荐资源

  1. 1
    difflib — SequenceMatcher (Built-in Fuzzy Matching)

    Python standard library module providing SequenceMatcher for computing similarity between sequences, built on an optimized Hunt-Szymanski algorithm. Zero dependencies and the fastest way to prototype fuzzy matching in Python.

    https://docs.python.org/3/library/difflib.html

  2. 2
    The Sequence Alignment Primer - Levenshtein & Dynamic Programming

    Comprehensive guide to sequence alignment algorithms (Levenshtein, Needleman-Wunsch, Smith-Waterman) with the mathematical foundations you need for understanding edit distance metrics — directly applicable to the fuzzy matching techniques in this article.

    https://academic.oup.com/femsre/article/28/5/573/540557

  3. 3
    Hands-On Machine Learning by Aurélien Géron - NLP Chapter (Ch. 10)

    O'Reilly's canonical practical ML text with a strong NLP chapter covering n-grams, embeddings, and similarity search at production scale — bridges the gap between textbook algorithms and real-world applications like deduplication and recommendation.

    https://github.com/ageron/handson-ml2

链接由 AI 推荐——使用前建议快速核实。