js实现fuzzywuzzy
JavaScript 实现模糊字符串匹配(FuzzyWuzzy)
使用 fuzzball.js 库
fuzzball.js 是 Python fuzzywuzzy 的 JavaScript 移植版本,支持多种模糊匹配算法。
安装:
npm install fuzzball
使用示例:

const fuzzball = require('fuzzball');
const string1 = "hello world";
const string2 = "hello there";
// 简单比率比较
const ratio = fuzzball.ratio(string1, string2);
console.log(`Ratio: ${ratio}`);
// 部分比率比较(子字符串匹配)
const partialRatio = fuzzball.partial_ratio(string1, string2);
console.log(`Partial Ratio: ${partialRatio}`);
// 令牌排序比率(忽略单词顺序)
const tokenSortRatio = fuzzball.token_sort_ratio(string1, string2);
console.log(`Token Sort Ratio: ${tokenSortRatio}`);
// 令牌集比率(匹配重复单词)
const tokenSetRatio = fuzzball.token_set_ratio(string1, string2);
console.log(`Token Set Ratio: ${tokenSetRatio}`);
使用 fast-fuzzy 库
fast-fuzzy 是另一个高性能的模糊搜索库,支持 Unicode 和多种匹配选项。
安装:

npm install fast-fuzzy
使用示例:
const { fuzzy } = require('fast-fuzzy');
const options = {
threshold: 0.6, // 匹配阈值
ignoreCase: true, // 忽略大小写
normalizeWhitespace: true // 标准化空格
};
const result = fuzzy("hello", "hlelo", options);
console.log(`Match score: ${result}`);
自定义实现(Levenshtein 距离)
如果需要轻量级实现,可以使用 Levenshtein 距离算法:
function levenshteinDistance(a, b) {
const matrix = [];
for (let i = 0; i <= b.length; i++) {
matrix[i] = [i];
}
for (let j = 0; j <= a.length; j++) {
matrix[0][j] = j;
}
for (let i = 1; i <= b.length; i++) {
for (let j = 1; j <= a.length; j++) {
if (b.charAt(i - 1) === a.charAt(j - 1)) {
matrix[i][j] = matrix[i - 1][j - 1];
} else {
matrix[i][j] = Math.min(
matrix[i - 1][j - 1] + 1,
matrix[i][j - 1] + 1,
matrix[i - 1][j] + 1
);
}
}
}
return matrix[b.length][a.length];
}
function similarity(a, b) {
const distance = levenshteinDistance(a, b);
return 1 - distance / Math.max(a.length, b.length);
}
console.log(similarity("kitten", "sitting")); // ~0.57
应用场景选择
- 简单字符串比较:使用
fuzzball.ratio或 Levenshtein 距离 - 包含子字符串的匹配:使用
fuzzball.partial_ratio - 单词顺序不同的文本:使用
fuzzball.token_sort_ratio - 大数据集搜索:使用
fast-fuzzy的性能优化版本
所有方案都支持处理 Unicode 字符,但需要注意不同库对特殊字符(如标点符号)的处理方式可能不同。






