找回密码
 注册
搜索
[新手上路]批处理新手入门导读[视频教程]批处理基础视频教程[视频教程]VBS基础视频教程[批处理精品]批处理版照片整理器
[批处理精品]纯批处理备份&还原驱动[批处理精品]CMD命令50条不能说的秘密[在线下载]第三方命令行工具[在线帮助]VBScript / JScript 在线参考
查看: 15190|回复: 0

[原创] vbs 实现 LD 算法

[复制链接]
发表于 2013-12-18 13:10:59 | 显示全部楼层 |阅读模式
本帖最后由 lxzzr 于 2014-7-12 19:54 编辑

LD算法(Levenshtein Distance)又成为编辑距离算法(Edit Distance)。他是以字符串A通过插入字符、删除字符、替换字符变成另一个字符串B,那么操作的过程的次数表示两个字符串的差异。

通俗点讲就是比较两个字符串的相似程度。

http://www.enun.net/?p=2442
  1. '======================
  2. '   A   t   e   s   t
  3. ' B 0   1   2   3   4
  4. '
  5. ' e 1   1   1   2   3
  6. '
  7. ' s 2   2   2   1   2
  8. '
  9. ' t 3   2   3   2   1
  10. '======================


  11. Wscript.Echo GetLevenshteinDistince("test", "est")

  12. '==============================================================
  13. ' Copyright (c) enun-net. All rights reserved.
  14. ' ScriptName: GetStrLD.vbs
  15. ' Creation Date: 10/11/2013
  16. ' Last Modified: 10/11/2013
  17. ' Author: 0x22e09
  18. ' Homepage: www.enun.net
  19. ' E-mail: 0x22e09@sina.com
  20. ' Description: Levenshtein Distance.
  21. '==============================================================

  22. Function GetLevenshteinDistince(str1, str2)
  23.         Dim x, y, A, B, C, K
  24.         Dim Matrix()
  25.         ReDim Matrix(Len(str2), Len(str1))
  26.        
  27.         '初始化第一行和第一列
  28.         For x = 0 To UBound(Matrix, 1)
  29.                 Matrix(x, 0) = x
  30.         Next
  31.         For y = 0 To UBound(Matrix, 2)
  32.                 Matrix(0, y) = y
  33.         Next

  34.         '填充矩阵
  35.         For x = 1 To UBound(Matrix, 1)
  36.                 For y = 1 To UBound(Matrix, 2)
  37.                         If (Mid(str1, Matrix(0, y), 1) = Mid(str2, Matrix(x, 0), 1)) Then
  38.                                 C = Matrix(x -1 ,y - 1)
  39.                         Else
  40.                                 C = Matrix(x -1 ,y - 1) + 1
  41.                         End If
  42.                        
  43.                         A = Matrix(x - 1, y) + 1
  44.                         B = Matrix(x, y - 1) + 1
  45.                        
  46.                         If (A =< B and A =< C) Then Matrix(x, y) = A
  47.                         If (B =< C and B =< A) Then Matrix(x, y) = B
  48.                         If (C =< A and C =< B) Then Matrix(x, y) = C
  49.                 Next
  50.         Next
  51.        
  52.         '计算 LD 值
  53.         If (Len(str1) > Len(str2)) Then
  54.                 K = Len(str1)
  55.         Else
  56.                 K = Len(str2)
  57.         End If

  58.         GetLevenshteinDistince = FormatNumber(1 - (Matrix(Len(str2), Len(str1)) / K), 3, True)
  59. End Function
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则

Archiver|手机版|小黑屋|批处理之家 ( 渝ICP备10000708号 )

GMT+8, 2026-3-16 22:41 , Processed in 0.017309 second(s), 7 queries , File On.

Powered by Discuz! X3.5

© 2001-2026 Discuz! Team.

快速回复 返回顶部 返回列表