要使用余弦相似度或Levenshtein距离来计算字符串之间的相似度,我们需要对字符串进行一些预处理。余弦相似度通常用于比较文档或句子,而Levenshtein距离用于计算两个字符串之间的编辑距离。下面我将分别展示如何使用这两种方法来对字符串数组进行分组。
使用Levenshtein距离
Levenshtein距离是指将一个字符串转换为另一个字符串所需的最少编辑操作次数(包括插入、删除和替换字符)。
function levenshteinDistance(a, b) {
if (a.length === 0) return b.length;
if (b.length === 0) return a.length;
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;
}
// 计算Levenshtein距离
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, // 替换
Math.min(
matrix[i][j - 1] + 1, // 插入
matrix[i - 1][j] + 1 // 删除
)
);
}
}
}
return matrix[b.length][a.length];
}
function groupByLevenshtein(strings, distanceThreshold) {
const groups = [];
strings.forEach((str, index) => {
let grouped = false;
for (let i = 0; i < groups.length; i++) {
const group = groups[i];
if (levenshteinDistance(str, group[0]) <= distanceThreshold) {
group.push(str);
grouped = true;
break;
}
}
if (!grouped) {
groups.push([str]);
}
});
return groups;
}
// 测试数据
const strings = ["apple", "apply", "appale", "orange", "orango", "banana", "bananb"];
const distanceThreshold = 2;
// 调用函数并打印结果
const groups = groupByLevenshtein(strings, distanceThreshold);
console.log(groups);
使用余弦相似度
余弦相似度通常用于比较文档或句子,它基于向量空间模型。为了使用余弦相似度,我们需要将字符串转换为向量。这通常涉及到将字符串分割成单词或字符,并创建一个表示每个单词或字符出现次数的向量。
function termFrequency(str) {
const terms = str.split('');
const frequency = {};
terms.forEach(term => {
frequency[term] = (frequency[term] || 0) + 1;
});
return frequency;
}
function cosineSimilarity(vecA, vecB) {
let dotProduct = 0;
let magnitudeA = 0;
let magnitudeB = 0;
for (let key in vecA) {
dotProduct += vecA[key] * (vecB[key] || 0);
magnitudeA += vecA[key] * vecA[key];
}
for (let key in vecB) {
magnitudeB += vecB[key] * vecB[key];
}
return dotProduct / (Math.sqrt(magnitudeA) * Math.sqrt(magnitudeB));
}
function groupByCosineSimilarity(strings, similarityThreshold) {
const groups = [];
const vectors = strings.map(termFrequency);
vectors.forEach((vector, index) => {
let grouped = false;
for (let i = 0; i < groups.length; i++) {
const group = groups[i];
if (cosineSimilarity(vector, vectors[group[0]]) >= similarityThreshold) {
group.push(index);
grouped = true;
break;
}
}
if (!grouped) {
groups.push([index]);
}
});
return groups.map(group => group.map(index => strings[index]));
}
// 测试数据
const strings = ["apple", "apply", "appale", "orange", "orango", "banana", "bananb"];
const similarityThreshold = 0.8; // 余弦相似度的范围是-1到1,接近1表示更相似
// 调用函数并打印结果
const groups = groupByCosineSimilarity(strings, similarityThreshold)
console.log(groups);