Wicked_Caty

Comparing strings

8 posts in this topic

I've just written a small script that compares two strings and returns the similarity of those two in %. I know of StringCompare, but I want to get a percentage and I also want to get in touch with Autoit.

Compiling doesn't cause any problems, but actually running it does. In line 20 it has a problem with the index and says "Subscript used on non-accessible variable". What's causing that problem, and how can I solve it? Thanks! And sorry for my ugly style

 

Similarity.au3

Share this post


Link to post
Share on other sites



Try this:
 

#include <MsgBoxConstants.au3>

Global $sTitle = "Similarity"
Global $tTextA = InputBox($sTitle, "Data 1: ")
Global $tTextB = InputBox($sTitle, "Data 2: ")
If $tTextA = $tTextB Then Exit MsgBox($MB_TOPMOST, $sTitle, "Smiler: 100%")
Local $nStringLenTextA = StringLen($tTextA)
Local $nStringLenTextB = StringLen($tTextB)
$tTextA = StringReplace($tTextA, " " & " ", " ")
Local $cSpit = StringInStr($tTextA, " ") ? " " : ""
Local $sSpitA = StringSplit($tTextA, $cSpit)
Local $Smiler = 0, $px = UBound($sSpitA)
For $i = 1 To $px - 1
    If StringInStr($tTextB, $sSpitA[$i]) Then $Smiler += 1
    ConsoleWrite($sSpitA[$i] & " : " & $tTextB & @CRLF)
Next
ConsoleWrite($px & @CRLF)
If $px > 3 Then $px -= 1
Local $SmilerPercent = ($Smiler * 100) / ($px - 1);$nStringLenTextB
If $SmilerPercent > 199 Then $SmilerPercent = 99
MsgBox($MB_TOPMOST, $sTitle, "Smiler: " & $SmilerPercent & "%")

Exit

 


Regards,
 

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

Wicked_Caty,

$a and $b are NOT arrays.  Try it using stringmid like this...

#include <MsgBoxConstants.au3>

$title = "Similarity"
;~ $a = InputBox($title, "Data 1")
;~ $b = InputBox($title, "Data 2")
local $a = 'abcd'

local $b = 'abce'

$n = 0
$la = StringLen($a)
$lb = StringLen($b)
$lc = ($la + $lb) / 2

If $la > $lb Then
   $l = $la
ElseIf $lb > $la Then
   $l = $lb

Else
   $l = $lc

EndIf



For $i = 1 To $l
    ConsoleWrite($i & @CRLF)
   If (stringmid($a,$i,1) = stringmid($b,$i,1)) Then
      $n = $n + 1
   EndIf

Next

$p = $n / $l * 100

MsgBox($MB_TOPMOST, $title, $a & @CRLF & $b & @CRLF & $title & ":" & @TAB & $p)

Exit

note: only strings of equal length tested...input supplied as strings, not user input

edit: also your loop should start at position "1" for strings

Edited by kylomas
additional info
1 person likes this

Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

I've just written a small script that compares two strings and returns the similarity of those two in %. I know of StringCompare, but I want to get a percentage and I also want to get in touch with Autoit.

Compiling doesn't cause any problems, but actually running it does. In line 20 it has a problem with the index and says "Subscript used on non-accessible variable". What's causing that problem, and how can I solve it? Thanks! And sorry for my ugly style

 

Similarity.au3

The problem is you're trying to use a variable that is not there.

You can solve it by ensuring you do not try to access a non existent variable.

Edited by JohnOne
1 person likes this

AutoIt Absolute Beginners    Require a serial    Pause Script    Video Tutorials by Morthawt   ipify 

Monkey's are, like, natures humans.

Share this post


Link to post
Share on other sites

Wicked_Caty,

Streamlined the code a bit.  If the string lengths are equal just use one or the other as the length value, no need to add them and divide by two.  I used a ternary expression to replace all of your length determination code...

#include <MsgBoxConstants.au3>

$title = "Similarity"
;~ $a = InputBox($title, "Data 1")
;~ $b = InputBox($title, "Data 2")
local $a = 'abcdf'

local $b = 'abce'



local $len_to_check = (stringlen($a) > stringlen($b)) ? stringlen($a) : stringlen($b), $p = 0, $n = 0

For $i = 1 To $len_to_check
   If (stringmid($a,$i,1) = stringmid($b,$i,1)) Then
      $n = $n + 1
   EndIf

Next

$p = $n / $len_to_check * 100

MsgBox($MB_TOPMOST, $title, $a & @CRLF & $b & @CRLF & $title & ":" & @TAB & $p)

Exit

Good Luck,

kylomas


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites

jguinch,

I believe you refer to my unifuzz SQLite extension; start reading here, then have luck finding the actual post where the extension resides later in this same thread. The new search feature is terrible. For the matter of string comparison outside of SQLite, this post may give something to work with.

1 person likes this

This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

According to the Levenshtein algorithm (https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#VBScript), from the VBS code :

$s1 = "My String 1"
$s2 = "My String 2 !"



Local $Levenshtein = Levenshtein($s1, $s2)

Local $iMaxLen = StringLen (  StringLen($s1) > StringLen($s2) ? $s1 : $s2 )
Local $percent = Round(($iMaxLen - $Levenshtein) * 100 / $iMaxLen, 2)

ConsoleWrite($percent & "%")


Func levenshtein( $a, $b )
    Local $i, $j, $cost, $d[1], $min1, $min2, $min3

    If StringLen( $a ) = 0 Then Return StringLen( $b )
    If StringLen( $b ) = 0 Then Return StringLen( $a )

    ReDim $d[ StringLen( $a ) + 1][ StringLen( $b ) + 1]

    For $i = 0 To StringLen( $a )
        $d[$i][0] = $i
    Next

    For $j = 0 To StringLen( $b )
        $d[ 0][$j] = $j
    Next

    For $i = 1 To StringLen( $a )
        For $j = 1 To StringLen( $b )
            $cost =  ( StringMid($a, $i, 1) = StringMid($b, $j, 1) ? 0 : 1)

            $min1 = $d[$i - 1][$j] + 1
            $min2 = $d[$i][$j - 1] + 1
            $min3 = $d[$i - 1][$j - 1] + $cost

            If $min1 <= $min2 And $min1 <= $min3 Then
                $d[$i][$j] = $min1
            ElseIf $min2 <= $min1 And $min2 <= $min3 Then
                $d[$i][$j] = $min2
            Else
                $d[$i][$j] = $min3
            EndIf
        Next
    Next

    Return $d[StringLen( $a )][StringLen( $b )]
EndFunc

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now

  • Similar Content

    • Dimmae
      By Dimmae
      Hello,
      at first: i'm new here, so please forgive me my mistakes, and show them to me, just that i can learn to do better in the future.
      Now to my Problem: i have an excel sheet, where i just need some columns for further actions, but i have no idea how to add single columns to a new array.
      I found the following code(the one i just added as a file) from 'water' in this forum, but i wont get how i could add multiple columns into a new array.
      The biggest problem in my situation is that i dont know the count of the rows i need for the array, i just got a fix number of rows, which is 4.
       
      Hope you can help me, and sry again for this 'unlucky illustration'.
       
      btw: how can i add code shown as code here, instead of posting it as a attached file?.
       
       
       
      autoit-select-column.au3
      defects.xlsx
    • czardas
      By czardas
      Haven't had much time to code recently. However the following thread inspired me.
      The debate about linear, parallel and binary search methods was rather interesting and, in an attempt to be diplomatic, I decided to combine @jchd's suggestion with @LarsJ's binary search example. I decided that the binary search algorithm required modification to make it more linear. As usual, 'if you invent something, it probably already exists and if it already exists, it exists for a reason'. My first attempt was not all that good. The code worked but was really a mess. I blame peer pressure (to post an example of a parallel search method).  I will delete that old code in due course.
      With a little memory jogging and a glance at the help file, the solution turned out to be quite easy: I just needed a better understanding of Euler. Further modification will be needed to work with more complicated unicode strings. The output could be returned as an array or a delimitered string. I'm not so interested in those details. I'm just going to post the algorithm for now and anyone, who wants to, can modify it to suit their needs. Both arrays must contain at least 1 element.
      Local $aFoo = [0,1,2,3,4,5,6,7,9,10,11,12,13,14,15,16,19,20,23,24,26,30,35,39,40,41] Local $aBar = [0,1,5,6,7,8,9,10,11,12,13,14,17,18,19,21,24,25,26,27,34,35,38,40] ParallelExponetialSearch($aFoo, $aBar) ; Compares two lists - returning positive matches. Each input array must be unique (individually) and in alphabetical order. Func ParallelExponetialSearch($aFoo, $aBar) Local $sFind, _ $iMin_F = -1, $iMax_F = UBound($aFoo) -1, $Lo_F = $iMin_F, $Hi_F, _ $iMin_B = -1, $iMax_B = UBound($aBar) -1, $Lo_B = $iMin_B, $Hi_B While $iMin_F < $iMax_F And $iMin_B < $iMax_B ; Toggle Arrays - Which array has most untested elements? This is the one we want to search next, ; so we can bypass more comparisons because (in theory) mismatches have a greater chance of being skipped. If $iMax_F - $iMin_F >= $iMax_B - $iMin_B Then ; $aFoo has more (or an equal number of) untested elements $Hi_F = $iMax_F $iMin_B += 1 $sFind = $aBar[$iMin_B] While $Lo_F < $Hi_F ; search $aFoo For $i = 0 To Floor(Log($Hi_F - $Lo_F) / Log(2)) $Lo_F = $iMin_F + 2^$i If $aFoo[$Lo_F] = $sFind Then $iMin_F = $Lo_F ; each match should be added to the output [perhaps an array] ConsoleWrite($sFind & " found at $aFoo[" & $Lo_F & "] = $aBar[" & $iMin_B & "]" & @LF) ExitLoop 2 ElseIf $aFoo[$Lo_F] > $sFind Then $Hi_F = $Lo_F -1 $iMin_F += Floor(2^($i -1)) $Lo_F = $iMin_F ContinueLoop 2 EndIf Next $iMin_F = $Lo_F ; minimum increment is one WEnd Else ; $aBar has more untested elements $Hi_B = $iMax_B $iMin_F += 1 $sFind = $aFoo[$iMin_F] While $Lo_B < $Hi_B ; search $aBar For $i = 0 To Floor(Log($Hi_B - $Lo_B) / Log(2)) $Lo_B = $iMin_B + 2^$i If $aBar[$Lo_B] = $sFind Then $iMin_B = $Lo_B ; each match should be added to the output [perhaps an array] ConsoleWrite($sFind & " found at $aFoo[" & $iMin_F & "] = $aBar[" & $Lo_B & "]" & @LF) ExitLoop 2 ElseIf $aBar[$Lo_B] > $sFind Then $Hi_B = $Lo_B -1 $iMin_B += Floor(2^($i -1)) $Lo_B = $iMin_B ContinueLoop 2 EndIf Next $iMin_B = $Lo_B ; minimum increment is one WEnd EndIf WEnd EndFunc ;==> ParallelExponetialSearch I hope this will be useful to someone. I believe it deserved a thread of its own!
    • cheeroke
      By cheeroke
      Hi all,
      I got this code and would like to be able to change Baud Rate and instead of sending character by character i would like to be able (if possible) to send whole string. But i don't know how to change it.
      I am taking input from file and processing whole line (this is done in FilesHandling.au3).
      To execute this i am just calling SendData("FileName", int) in "main" script.
      Any help very appreciated.
      #include <WinAPI.au3> #include <Array.au3> #include "FilesHandling.au3" ;init DLL function, we need handle to call the function $h = DllCall("Kernel32.dll", "hwnd", "CreateFile", "str", "\\.\COM19", "int", BitOR($GENERIC_READ,$GENERIC_WRITE), "int", 0, "ptr", 0, "int", $OPEN_EXISTING, "int", $FILE_ATTRIBUTE_NORMAL, "int", 0) $handle=$h[0] Func SendData($FileName, $LineNumber) ;string to be send $c = readFile($FileName, $LineNumber) $cLenght = StringLen($c) $aArray = StringSplit($c, "") ;_ArrayDisplay($aArray, "", Default, 64) For $i = 1 To $cLenght writeChar($handle, $aArray[$i], $cLenght) Next ;move to next line writeChar($handle, @CR,1) EndFunc ;write a single char func writeChar($handle,$c,) $stString = DLLStructCreate("char str") $lpNumberOfBytesWritten = 0 DllStructSetData($stString, 1, $c) $res = _WinAPI_WriteFile($handle, DllStructGetPtr($stString, "str"), 1,$lpNumberOfBytesWritten) if ($res<>true) then ConsoleWrite ( _WinAPI_GetLastErrorMessage() & @LF) EndIf EndFunc  
    • RC86
      By RC86
      Afternoon!
      I have a requirement to return both a string and an array from a function so as a result I put them both into an array and returned that.  I can access them in their entirety after returning them but then I can't seem to access the array elements after this.  Should I be able to or is there a prettier way?
      #include <Array.au3> ;Memory info returned as a string and an array $memoryInfo = _getMemoryInfo() msgbox(0,"Memory Info",$memoryInfo[0]) _ArrayDisplay($memoryInfo[1],"Memory as an Array") Local $newArray[7] $memoryInfo[1] = $newArray msgbox(0,"Test element",$newArray[0]) _ArrayDisplay($newArray) Func _getMemoryInfo() Local $newArray[7] Local $array = MemGetStats() $newArray[0] = $array[0] ;% of memory in use $newArray[1] = Round($array[1]/1024 * 0.001,2) ;Total physical RAM $newArray[2] = Round($array[2]/1024 * 0.001,2) ;Availaible physical RAM $newArray[3] = Round($array[3]/1024 * 0.001,2) ;Total pagefile $newArray[4] = Round($array[4]/1024 * 0.001,2) ;Available pagefile $newArray[5] = Round($array[5]/1024 * 0.001,2) ;Total virtual $newArray[6] = Round($array[6]/1024 * 0.001,2) ;Available virtual $memoryUsage = $newArray[1] - $newarray[2] $pagefileUsage = $newArray[3] - $newarray[4] ;Output/Return Local $returnArray[2] $returnArray[0] = "Memory: " & $memoryUsage & " GB/" & $newArray[1] & " GB " & @CRLF & "Pagefile: " & $pagefileUsage & " GB/" & $newArray[3] & " GB " $returnArray[1] = $newArray return $returnArray EndFunc A bit messy but hopefully it's understandable what I'm trying to achieve.
      Thanks!
    • FroVN
      By FroVN
      Hi, i have a problem :" can't set the name of file with a special character like: \;/;";|;...  have anyway to short the StringInSrt and Stringreplace? i am using this code but too long
      $title=InputBox(0,'','','')
         if StringInStr($title,'\') or StringInStr($title,'/') or StringInStr($title,':') or StringInStr($title,'*') or StringInStr($title,'?') or StringInStr($title,'"') or StringInStr($title,'<') or StringInStr($title,'>') or StringInStr($title,'|') Then
             $title=StringReplace($title,'\','-')
              $title=StringReplace($title,'/','-')
               $title=StringReplace($title,':','-')
                $title=StringReplace($title,'*','-')
                 $title=StringReplace($title,'?','-')
                  $title=StringReplace($title,'"','-')
                   $title=StringReplace($title,'<','-')
                    $title=StringReplace($title,'>','-')
                     $title=StringReplace($title,'|','-')
         EndIf