我需要测量名称以字符串形式提供的两个地方之间的物理距离。由于有时名称的写法略有不同,我一直在寻找一个可以帮助我测量差异的库,然后将其与纬度和经度的测量相结合以选择正确的匹配项。首选语言:Java 或 PHP。
有什么建议么?
看看Levenshtein 距离。这是一种衡量两个字符串彼此之间差异程度的方法。
希望我正确理解了您的问题;在与“纬度和经度”相同的句子中使用“距离”可能会造成混淆!
虽然是用 c 编写的(使用 python 和 tcl 绑定),但 libdistance将是一个在字符串/数据上应用多个距离度量的工具。
指标包括:
我冒昧地将我为计算 Levenshtein 距离而编写的一段 C# 代码翻译成 Java 代码。它只使用两个交替的一维数组,而不是一个大的锯齿状数组:
public static int getDifference(String a, String b)
{
// Minimize the amount of storage needed:
if (a.length() > b.length())
{
// Swap:
String x = a;
a = b;
b = x;
}
// Store only two rows of the matrix, instead of a big one
int[] mat1 = new int[a.length() + 1];
int[] mat2 = new int[a.length() + 1];
int i;
int j;
for (i = 1; i <= a.length(); i++)
mat1[i] = i;
mat2[0] = 1;
for (j = 1; j <= b.length(); j++)
{
for (i = 1; i <= a.length(); i++)
{
int c = (a.charAt(i - 1) == b.charAt(j - 1) ? 0 : 1);
mat2[i] =
Math.min(mat1[i - 1] + c,
Math.min(mat1[i] + 1, mat2[i - 1] + 1));
}
// Swap:
int[] x = mat1;
mat1 = mat2;
mat2 = x;
mat2[0] = mat1[0] + 1;
}
// It's row #1 because we swap rows at the end of each outer loop,
// as we are to return the last number on the lowest row
return mat1[a.length()];
}
它没有经过严格的测试,但似乎可以正常工作。它基于我为大学练习制作的 Python 实现。希望这可以帮助!
您可能会使用语音算法找到一些拼写错误的名称,从而获得一些不错的结果。
此外,如果您使用更机械的编辑距离,您可能会使用考虑键盘几何形状的加权函数看到更好的结果(即物理上靠近的键比远离的键“更便宜”替换)。顺便说一句,这是一种专利方法,所以要小心不要写太流行的东西;)
我在 Java 中找到了 SumMetrics,但没有使用它。
我会推荐Levenshtein Distance或Jaccard Distance来比较文本。