我一直在使用Levenstein距离来衡量两个字符串的相似性。
int ComputeLevenshteinDistance(string source, string target)
{
if ((source == null) || (target == null)) return 0;
if ((source.Length == 0) || (target.Length == 0)) return 0;
if (source == target) return source.Length;
int sourceWordCount = source.Length;
int targetWordCount = target.Length;
// Step 1
if (sourceWordCount == 0)
return targetWordCount;
if (targetWordCount == 0)
return sourceWordCount;
int[,] distance = new int[sourceWordCount + 1, targetWordCount + 1];
// Step 2
for (int i = 0; i <= sourceWordCount; distance[i, 0] = i++);
for (int j = 0; j <= targetWordCount; distance[0, j] = j++);
for (int i = 1; i <= sourceWordCount; i++)
{
for (int j = 1; j <= targetWordCount; j++)
{
// Step 3
int cost = (target[j - 1] == source[i - 1]) ? 0 : 1;
// Step 4
distance[i, j] = Math.Min(Math.Min(distance[i - 1, j] + 1, distance[i, j - 1] + 1), distance[i - 1, j - 1] + cost);
}
}
return distance[sourceWordCount, targetWordCount];
}
但我想修改或编写一个新代码来测量两个字符串的语义相似度,并给出百分比。
我试图在网上搜索一些代码示例,但很难找到一个具有一些语义相似度测量功能的简单代码。
这样做的简单方法是什么?
答案 0 :(得分:0)
我自己使用算法来找到最接近的字符串。它在ICR / OCR文档中非常有用。要排序字符串我必须按相似性排序字符串,仅根据编辑距离排序输入是不够的。我想,在两个字符串归一化的情况下,两个给定字符串之间的最大编辑距离等于最长字符串的长度,而最小值则为零。所以,我刚刚将编辑距离转换为百分比,将其除以最大距离。
这是一个天真的解决方案,但它的效果非常好。在ICR / OCR中,我们有一些误报,例如h
变为ln
,m
变为rn
等等......我不必担心它们,不再担心它们了。
PS:在我的例子中,字符串规范化是删除所有符号,并转换为大写ASCII字母。