[英]Measuring the semantic similarity of two strings in c#
我一直在使用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];
}
但我想修改或编写新代码,以给出百分比的方式测量两个字符串的语义相似性。
我试图在Web上搜索一些代码示例,但是很难找到一个具有语义相似性度量功能的简单示例。
有什么简单明了的方法?
我本人已使用该算法来找到最接近的字符串。 在ICR / OCR文档中,它非常有用。 要对字符串进行排序,我必须按相似性对字符串进行排序,仅基于编辑距离对输入进行排序是不够的。 在对两个字符串进行归一化的情况下,我计算出两个给定字符串之间的最大编辑距离等于最长字符串的长度,而最小值则为零。 因此,我刚刚将编辑距离除以最大距离,将其转换为百分比。
这是一个幼稚的解决方案,但效果非常好。 在ICR / OCR中,我们有一些误报,例如h
变为ln
, m
变为rn
,等等...我不必担心它们,现在不再担心。
PS:就我而言,字符串标准化是删除所有符号,然后转换为大写ASCII字母。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.