Skip to content

Instantly share code, notes, and snippets.

@jstemerdink
Created November 12, 2019 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jstemerdink/04452be456a16fa0d16ca5ca929b4225 to your computer and use it in GitHub Desktop.
Save jstemerdink/04452be456a16fa0d16ca5ca929b4225 to your computer and use it in GitHub Desktop.
Auto correct the query before sending it to your search engine

Auto correct a query before sending it to your search engine

Read my blog here

Powered by ReSharper image

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