`
biansutao
  • 浏览: 53472 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

字符串相似度算法 levenshtein distance 编辑距离算法

阅读更多
参考:http://www.merriampark.com/ld.htm#WHATIS
http://en.wikipedia.org/wiki/Levenshtein_distance
 
    * Java
    * C++
    * Visual Basic
    * Python

Java

public class Distance {

  //****************************
  // Get minimum of three values
  //****************************

  private int Minimum (int a, int b, int c) {
  int mi;

    mi = a;
    if (b < mi) {
      mi = b;
    }
    if (c < mi) {
      mi = c;
    }
    return mi;

  }

  //*****************************
  // Compute Levenshtein distance
  //*****************************

  public int LD (String s, String t) {
  int d[][]; // matrix
  int n; // length of s
  int m; // length of t
  int i; // iterates through s
  int j; // iterates through t
  char s_i; // ith character of s
  char t_j; // jth character of t
  int cost; // cost

    // Step 1

    n = s.length ();
    m = t.length ();
    if (n == 0) {
      return m;
    }
    if (m == 0) {
      return n;
    }
    d = new int[n+1][m+1];

    // Step 2

    for (i = 0; i <= n; i++) {
      d[i][0] = i;
    }

    for (j = 0; j <= m; j++) {
      d[0][j] = j;
    }

    // Step 3

    for (i = 1; i <= n; i++) {

      s_i = s.charAt (i - 1);

      // Step 4

      for (j = 1; j <= m; j++) {

        t_j = t.charAt (j - 1);

        // Step 5

        if (s_i == t_j) {
          cost = 0;
        }
        else {
          cost = 1;
        }

        // Step 6

        d[i][j] = Minimum (d[i-1][j]+1, d[i][j-1]+1, d[i-1][j-1] + cost);

      }

    }

    // Step 7

    return d[n][m];

  }

}

C++

In C++, the size of an array must be a constant, and this code fragment causes an error at compile time:

int sz = 5;
int arr[sz];

This limitation makes the following C++ code slightly more complicated than it would be if the matrix could simply be declared as a two-dimensional array, with a size determined at run-time.

In C++ it's more idiomatic to use the System Template Library's vector class, as Anders Sewerin Johansen has done in an alternative C++ implementation.

Here is the definition of the class (distance.h):

class Distance
{
  public:
    int LD (char const *s, char const *t);
  private:
    int Minimum (int a, int b, int c);
    int *GetCellPointer (int *pOrigin, int col, int row, int nCols);
    int GetAt (int *pOrigin, int col, int row, int nCols);
    void PutAt (int *pOrigin, int col, int row, int nCols, int x);
}; 

Here is the implementation of the class (distance.cpp):

#include "distance.h"
#include <string.h>
#include <malloc.h>

//****************************
// Get minimum of three values
//****************************

int Distance::Minimum (int a, int b, int c)
{
int mi;

  mi = a;
  if (b < mi) {
    mi = b;
  }
  if (c < mi) {
    mi = c;
  }
  return mi;

}

//**************************************************
// Get a pointer to the specified cell of the matrix
//************************************************** 

int *Distance::GetCellPointer (int *pOrigin, int col, int row, int nCols)
{
  return pOrigin + col + (row * (nCols + 1));
}

//*****************************************************
// Get the contents of the specified cell in the matrix 
//*****************************************************

int Distance::GetAt (int *pOrigin, int col, int row, int nCols)
{
int *pCell;

  pCell = GetCellPointer (pOrigin, col, row, nCols);
  return *pCell;

}

//*******************************************************
// Fill the specified cell in the matrix with the value x
//*******************************************************

void Distance::PutAt (int *pOrigin, int col, int row, int nCols, int x)
{
int *pCell;

  pCell = GetCellPointer (pOrigin, col, row, nCols);
  *pCell = x;

}

//*****************************
// Compute Levenshtein distance
//*****************************

int Distance::LD (char const *s, char const *t)
{
int *d; // pointer to matrix
int n; // length of s
int m; // length of t
int i; // iterates through s
int j; // iterates through t
char s_i; // ith character of s
char t_j; // jth character of t
int cost; // cost
int result; // result
int cell; // contents of target cell
int above; // contents of cell immediately above
int left; // contents of cell immediately to left
int diag; // contents of cell immediately above and to left
int sz; // number of cells in matrix

  // Step 1	

  n = strlen (s);
  m = strlen (t);
  if (n == 0) {
    return m;
  }
  if (m == 0) {
    return n;
  }
  sz = (n+1) * (m+1) * sizeof (int);
  d = (int *) malloc (sz);

  // Step 2

  for (i = 0; i <= n; i++) {
    PutAt (d, i, 0, n, i);
  }

  for (j = 0; j <= m; j++) {
    PutAt (d, 0, j, n, j);
  }

  // Step 3

  for (i = 1; i <= n; i++) {

    s_i = s[i-1];

    // Step 4

    for (j = 1; j <= m; j++) {

      t_j = t[j-1];

      // Step 5

      if (s_i == t_j) {
        cost = 0;
      }
      else {
        cost = 1;
      }

      // Step 6 

      above = GetAt (d,i-1,j, n);
      left = GetAt (d,i, j-1, n);
      diag = GetAt (d, i-1,j-1, n);
      cell = Minimum (above + 1, left + 1, diag + cost);
      PutAt (d, i, j, n, cell);
    }
  }

  // Step 7

  result = GetAt (d, n, m, n);
  free (d);
  return result;
	
}

Visual Basic

'*******************************
'*** Get minimum of three values
'*******************************

Private Function Minimum(ByVal a As Integer, _
                         ByVal b As Integer, _
                         ByVal c As Integer) As Integer
Dim mi As Integer
                          
  mi = a
  If b < mi Then
    mi = b
  End If
  If c < mi Then
    mi = c
  End If
  
  Minimum = mi
                          
End Function

'********************************
'*** Compute Levenshtein Distance
'********************************

Public Function LD(ByVal s As String, ByVal t As String) As Integer
Dim d() As Integer ' matrix
Dim m As Integer ' length of t
Dim n As Integer ' length of s
Dim i As Integer ' iterates through s
Dim j As Integer ' iterates through t
Dim s_i As String ' ith character of s
Dim t_j As String ' jth character of t
Dim cost As Integer ' cost
  
  ' Step 1
  
  n = Len(s)
  m = Len(t)
  If n = 0 Then
    LD = m
    Exit Function
  End If 
  If m = 0 Then
    LD = n
    Exit Function
  End If 
  ReDim d(0 To n, 0 To m) As Integer
  
  ' Step 2
  
  For i = 0 To n
    d(i, 0) = i
  Next i
  
  For j = 0 To m
    d(0, j) = j
  Next j

  ' Step 3

  For i = 1 To n
    
    s_i = Mid$(s, i, 1)
    
    ' Step 4
    
    For j = 1 To m
      
      t_j = Mid$(t, j, 1)
      
      ' Step 5
      
      If s_i = t_j Then
        cost = 0
      Else
        cost = 1
      End If
      
      ' Step 6
      
      d(i, j) = Minimum(d(i - 1, j) + 1, d(i, j - 1) + 1, d(i - 1, j - 1) + cost)
    
    Next j
    
  Next i
  
  ' Step 7
  
  LD = d(n, m)
  Erase d

End Function





#!/user/bin/env python
# -*- coding: utf-8 -*-

class arithmetic():
	
	def __init__(self):
		pass
	''' 【编辑距离算法】 【levenshtein distance】 【字符串相似度算法】 '''
	def levenshtein(self,first,second):
		if len(first) > len(second):
			first,second = second,first
		if len(first) == 0:
			return len(second)
		if len(second) == 0:
			return len(first)
		first_length = len(first) + 1
		second_length = len(second) + 1
		distance_matrix = [range(second_length) for x in range(first_length)] 
		#print distance_matrix
		for i in range(1,first_length):
			for j in range(1,second_length):
				deletion = distance_matrix[i-1][j] + 1
				insertion = distance_matrix[i][j-1] + 1
				substitution = distance_matrix[i-1][j-1]
				if first[i-1] != second[j-1]:
					substitution += 1
				distance_matrix[i][j] = min(insertion,deletion,substitution)
		print distance_matrix
		return distance_matrix[first_length-1][second_length-1]
	
if __name__ == "__main__":
	arith = arithmetic()
	print arith.levenshtein('GUMBOsdafsadfdsafsafsadfasfadsfasdfasdfs','GAMBOL00000000000dfasfasfdafsafasfasdfdsa'

  • ld.rar (6 KB)
  • 下载次数: 47
分享到:
评论
1 楼 junfeng_feng 2012-12-10  
这个Pytrhon代码不知道起源在在哪?

distance_matrix 没有初始化正确。
应该初始化为:
0,1,2,3,4
1,
2,
3,

相关推荐

    Python-Levenshtein快速计算编辑距离以及字符串的相似度

    除了编辑距离外,Levenshtein库还提供了其他有用的功能,如`ratio`函数,它能计算两个字符串的相似度,返回值范围在0到1之间,值越接近1表示相似度越高: ```python from Levenshtein import ratio ratio('kitten',...

    两个字符串的相似度算法实现——编辑距离之Levenshtein距离

    两个字符串的相似度算法实现——编辑距离之Levenshtein距离

    字符串相似度算法

    在IT领域,字符串相似度算法是一种非常重要的工具,特别是在数据挖掘、信息检索、文本分类以及自然语言处理等应用中。这个小例子旨在介绍如何通过计算字符串间的相似度来进行模糊匹配。我们将探讨几种常见的字符串...

    C#,字符串相似度的莱文斯坦距离(Levenshtein Distance)算法与源代码

    C#,字符串相似度的莱文斯坦距离(Levenshtein Distance)算法与源代码 莱文斯坦距离(Levenshtein Distance)用于衡量两个字符串之间的相似度。 莱文斯坦距离以俄国科学家(Vladimir I. Levenshtein)命名,他于...

    Delphi计算字符串的相似度

    总之,Delphi提供了丰富的工具和功能来处理字符串相似度计算,开发者可以根据具体需求选择合适的算法并进行实现。在实际项目中,理解和运用这些算法可以帮助我们更好地理解和比较文本数据,提升应用程序的功能和用户...

    mysql 计算字符串相似度

    1. **使用更高效的算法**:例如,采用编辑距离算法(Levenshtein 距离)或 Jaccard 相似度等更复杂的相似度计算方法。 2. **利用 MySQL 的内置函数**:例如,尝试使用 `UNHEX()` 和 `HEX()` 函数来处理多字节字符。 ...

    数据挖掘与数据分析应用案例 数据挖掘算法实践基于Java的文本相似度(Levenshtein distance算法)计算.doc

    Levenshtein Distance算法,也称为编辑距离算法,由俄罗斯科学家Vladimir Levenshtein于1965年提出。这种算法的核心思想在于计算两个字符串之间的最小编辑距离,即通过最少的编辑操作(包括替换、插入、删除字符)将...

    使用最短编辑距离算法判断两个字符串的相似度

    总之,最短编辑距离算法是计算字符串相似度的一种基础且重要的方法,它在文本处理领域有着广泛的应用。理解和掌握这一算法,对于开发相关的软件功能,如自动纠错、搜索引擎优化等,都是非常有益的。

    LD的两字符串相似度计算.zip

    Levenshtein Distance(简称LD),又称编辑距离,是衡量两个字符串相似度的一种方法。这个概念由俄国科学家Vladimir Levenshtein在1965年提出,因此得名。 编辑距离定义了将一个字符串转换成另一个字符串所需的最少...

    c#字符串相似度源码 编辑距离 余弦相似性 SimHash

    本文将详细解析C#编程语言中实现的四种字符串相似度计算方法:编辑距离(Levenshtein Distance)、余弦相似性(Cosine Similarity)以及SimHash算法。 首先,编辑距离是一种衡量两个字符串之间差异的度量,它表示由...

    字符串相似度比较

    本文将深入探讨字符串相似度比较的概念、常用算法以及在JavaScript中的实现,同时关注潜在的性能和内存管理问题。 字符串相似度比较旨在量化两个或多个字符串之间的相似程度,通常以百分比形式表示。这种比较不仅...

    字符串相似度比较T-2021-7-1.rar

    总的来说,字符串相似度比较是信息技术中的基础工具,深入理解和灵活运用这些算法能帮助我们解决多种实际问题。通过“字符串相似度比较T-2021-7-1.rar”中的内容,我们可以系统学习这一领域的知识,提升处理文本数据...

    计算字符串相似度(支持中英文,编辑距离算法,余弦,繁体转简体)

    在IT领域,字符串相似度计算是一项重要的技术,广泛应用于文本分析、信息检索、自然语言处理等多个方面。本项目提供了一个简单易用的demo,支持中英文字符串的相似度比较,采用了编辑距离算法和余弦相似度这两种经典...

    Java字符串相似度:各种字符串相似度和距离算法的实现:Levenshtein,Jaro-winkler,n-Gram,Q-Gram,Jaccard索引,最长公共子序列编辑距离,余弦相似度..

    当前实现了十二种算法(包括Levenshtein编辑距离和同级,Jaro-Winkler,最长公共子序列,余弦相似性等)。 查看下面的摘要表以获取完整列表... 下载 使用Maven: &lt;groupId&gt;info.debatty &lt;artifactId&gt;java-...

    字符串的相似度 编辑距离 java实现

    字符串相似度计算之编辑距离 编辑距离(Edit Distance)是计算两个字符串之间的相似度的算法,它定义了从原串(s)转换到目标串(t)所需要的最少的插入、删除和替换的数目。在自然语言处理(NLP)中应用非常广泛,...

    Oracle字符相似度函数

    - **EDITDISTANCE()**:编辑距离(Levenshtein距离)函数,计算将一个字符串转换为另一个字符串所需的最少单字符编辑(插入、删除或替换)次数。返回值是具体的编辑距离,数值越小表示越接近。 在实际应用中,...

    编辑长求字符串相似度Delphi源代码

    首先,我们需要了解几种常见的字符串相似度算法: 1. **Levenshtein距离**:这个算法衡量的是通过插入、删除或替换操作将一个字符串转换成另一个字符串所需的最少步骤数。在Delphi中,你可以创建一个动态数组来存储...

    LevenshteinDistance(编辑距离)算法详解[借鉴].pdf

    Levenshtein Distance 算法是一种计算两个字符串之间的编辑距离的算法,编辑距离是指从一个字符串变换到另一个字符串所需要的最少变化操作步骤。该算法的计算过程可以用一个二维表来理解,以beauty 和 batyu为例: ...

Global site tag (gtag.js) - Google Analytics