Created
August 29, 2020 00:02
-
-
Save M1kep/620a60c022a96707c3d4af77f9745721 to your computer and use it in GitHub Desktop.
PowerShell "Spell Check"
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add-Type @" | |
using System.Linq; | |
using System; | |
public class EditDistance { | |
public static int CheckEditDistance (string original, string modified) | |
{ | |
int len_orig = original.Length; | |
int len_diff = modified.Length; | |
var matrix = new int[len_orig + 1, len_diff + 1]; | |
for (int i = 0; i <= len_orig; i++) | |
matrix[i,0] = i; | |
for (int j = 0; j <= len_diff; j++) | |
matrix[0,j] = j; | |
for (int i = 1; i <= len_orig; i++) { | |
for (int j = 1; j <= len_diff; j++) { | |
int cost = modified[j - 1] == original[i - 1] ? 0 : 1; | |
var vals = new int[] { | |
matrix[i - 1, j] + 1, | |
matrix[i, j - 1] + 1, | |
matrix[i - 1, j - 1] + cost | |
}; | |
matrix[i,j] = vals.Min (); | |
if (i > 1 && j > 1 && original[i - 1] == modified[j - 2] && original[i - 2] == modified[j - 1]) | |
matrix[i,j] = Math.Min (matrix[i,j], matrix[i - 2, j - 2] + cost); | |
} | |
} | |
return matrix[len_orig, len_diff]; | |
} | |
} | |
"@ -Language CSharp -ReferencedAssemblies System.Xml, System.Xml.Linq, System.Linq, System.Runtime.Extensions | |
<# | |
.SYNOPSIS | |
Provides basic "Spell Checking" | |
.DESCRIPTION | |
Returns the $ResultSize strings from the dictionart that are closest to the BaseString using the Levenshtein distance | |
.PARAMETER BaseString | |
The string to be checked for closes matches | |
.PARAMETER Dictionary | |
The dictionary used for lookup | |
.PARAMETER ResultSize | |
The number of results to be returned | |
.EXAMPLE | |
PS C:\> Get-ClosestString -BaseString 'Value1' -Dictionary $value2 | |
.NOTES | |
Additional information about the function. | |
#> | |
function Get-ClosestString { | |
[CmdletBinding()] | |
param | |
( | |
[Parameter(Mandatory = $true)] | |
[String]$BaseString, | |
[Parameter(Mandatory = $true)] | |
[String[]]$Dictionary, | |
[int]$ResultSize = 2 | |
) | |
$BaseString = $BaseString.ToLower() | |
$Comparisons = $Dictionary | ForEach-Object { | |
[PSCustomObject]@{ | |
Distance = [EditDistance]::CheckEditDistance($BaseString, $_.ToLower()) | |
Word = $_ | |
} | |
} | |
$Comparisons | Sort-Object Distance | Select-Object -First $ResultSize | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment