Skip to content

Instantly share code, notes, and snippets.

@JohnLBevan
Last active April 18, 2018 13:24
Show Gist options
  • Save JohnLBevan/c00a02361d4d0a331746995314ad8b58 to your computer and use it in GitHub Desktop.
Save JohnLBevan/c00a02361d4d0a331746995314ad8b58 to your computer and use it in GitHub Desktop.
Get a list of synonyms for a given term. This is heavily based on code from a question here: https://stackoverflow.com/q/49899308/361842
void Main()
{
using (var thesaurus = new Thesaurus())
{
foreach (var term in (new string[]{"dictionary","hot","actor","code"}))
{
Debug.WriteLine(term);
foreach (var value in thesaurus.GetSynonyms(term))
{
Debug.WriteLine($"- {value}");
}
}
}
}
public class Thesaurus: IDisposable
{
private Microsoft.Office.Interop.Word.Application appWord;
private object objLanguage;
public Thesaurus()
{
appWord = new Microsoft.Office.Interop.Word.Application();
objLanguage = Microsoft.Office.Interop.Word.WdLanguageID.wdEnglishUS;
}
public IEnumerable<string> GetSynonyms(string term)
{
var si = appWord.get_SynonymInfo(term, ref (objLanguage)); //Microsoft.Office.Interop.Word.SynonymInfo
foreach (var meaning in (si.MeaningList as Array))
{
yield return meaning.ToString();
}
System.Runtime.InteropServices.Marshal.ReleaseComObject(si);
si = null;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
objLanguage = null;
if (disposing)
{
if (appWord != null)
{
appWord.Quit(); //if this isn't called, you'll see winword.exe hanging around in your processes
System.Runtime.InteropServices.Marshal.ReleaseComObject(appWord);
}
GC.Collect();
GC.WaitForPendingFinalizers();
}
appWord = null;
}
}
@JohnLBevan
Copy link
Author

Output of above example:

dictionary
- lexicon
hot
- warm
- sweltering
- spicy
- passionate
actor
- performer
code
- cypher
- program
- system
- cypher

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment