Read my blog here
Created
November 12, 2019 14:30
-
-
Save jstemerdink/04452be456a16fa0d16ca5ca929b4225 to your computer and use it in GitHub Desktop.
Auto correct the query before sending it to your search engine
This file contains hidden or 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
public string AutoCorrect(string query) | |
{ | |
if (query.Length < 5) | |
{ | |
return query; | |
} | |
SpellCheckClient spellCheckClient = new SpellCheckClient(new ApiKeyServiceClientCredentials("Your_BING_SpellCheck_Key_Here")); | |
HttpOperationResponse<SpellCheckModel> result = spellCheckClient.SpellCheckerWithHttpMessagesAsync(text: query, mode: "spell", setLang: ContentLanguage.PreferredCulture.TwoLetterISOLanguageName).Result; | |
IList<SpellingFlaggedToken> tokens = result.Body.FlaggedTokens; | |
if (tokens.Count == 0) | |
{ | |
return query; | |
} | |
string autoCorrect = query; | |
int diff = 0; | |
foreach (SpellingFlaggedToken problemToken in tokens) | |
{ | |
int offset = problemToken.Offset; | |
int originalTokenLength = problemToken.Token.Length; | |
SpellingTokenSuggestion suggestionToken = problemToken.Suggestions[0]; | |
if (suggestionToken.Score < .5) | |
{ | |
continue; | |
} | |
string suggestion = suggestionToken.Suggestion; | |
int lengthDiff = suggestion.Length - originalTokenLength; | |
autoCorrect = autoCorrect.Substring(0, offset + diff) + suggestion + autoCorrect.Substring(offset + diff + originalTokenLength); | |
diff += lengthDiff; | |
} | |
return autoCorrect; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment