Skip to content

Instantly share code, notes, and snippets.

@PrateekKumarSingh
Last active March 27, 2019 16:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save PrateekKumarSingh/1cb264e6e2eb8b2832e9 to your computer and use it in GitHub Desktop.
Save PrateekKumarSingh/1cb264e6e2eb8b2832e9 to your computer and use it in GitHub Desktop.
Function Check-Spelling()
{
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=0,ValueFromPipeline=$True)]
[String] $String,
[Switch] $ShowErrors,
[Switch] $RemoveSpecialChars
)
Process{
If($RemoveSpecialChars){ $String = Clean-String $String }
Foreach($S in $String)
{
$SplatInput = @{
Uri= "https://api.projectoxford.ai/text/v1.0/spellcheck?Proof"
Method = 'Post'
}
$Headers = @{'Ocp-Apim-Subscription-Key' = "XXXXXXXXXXXXXXXXXXXXXXXXXX"}
$body = @{'text'=$s }
Try{
$SpellingErrors = (Invoke-RestMethod @SplatInput -Headers $Headers -Body $body ).SpellingErrors
$OutString = $String # Make a copy of string to replace the errorswith suggestions.
If($SpellingErrors) # If Errors are Found
{
# Nested Foreach to generate the Rectified string Post Spell-Check
Foreach($E in $spellingErrors){
If($E.Type -eq 'UnknownToken') # If an unknown word identified, replace it with the respective sugeestion from the API results
{
$OutString= Foreach($s in $E.suggestions.token)
{
$OutString -replace $E.token, $s
}
}
Else # If REPEATED WORDS then replace the set by an instance of repetition
{
$OutString = $OutString -replace "$($E.token) $($E.token) ", "$($E.token) "
}
}
# InCase ShowErrors switch is ON
If($ShowErrors -eq $true)
{
return $SpellingErrors |select @{n='ErrorToken';e={$_.Token}},@{n='Type';e={$_.Type}}, @{n='Suggestions';e={($_.suggestions).token|?{$_ -ne $null}}}
}
Else # Else return the spell checked string
{
Return $OutString
}
}
else # When No error is found in the input string
{
Return "No errors found in the String."
}
}
Catch{
"Something went wrong, please try running the script again"
}
}
}
}
# Function to Remove special character s and punctuations from Input string
Function Clean-String($Str)
{
Foreach($Char in [Char[]]"!@#$%^&*(){}|\/?><,.][+=-_"){$str=$str.replace("$Char",'')}
Return $str
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment