How to select a random word from WordNet Library C#

104 Views Asked by At

I am making a word quiz game in Visual Studio 2022. I have found a way to check if a word is a real word using WordNet database files.

My question is how to select a random word from WordNet in order to make user guess it. Method like wordNet.GetAllSynsets(); does not exist. I have only found wordNet.AllWords; that is more like what I want. But I don't know how to work with it.

1

There are 1 best solutions below

0
Jonathan On

When you look at the NuGet page of that package, you'll see it has been deprecated. This means it will not be updated anymore and you should search for another package or solution.
As most dictionaries are very big, it would be a better practice to call an API, like dictionaryAPI.dev. I'm not sure what .NET version you are using, but I'll go with .net 7.

This API returns a 404 Status Code if a word does not exist. This means we can simply check if it returns a statuscode that indicates success, which the HttpResponse has a builtin property for.

    public class WordChecker : IDisposable
    {
        HttpClient httpClient;
        // the base URL for the API
        const string baseUrl = "https://api.dictionaryapi.dev/api/v2/entries/en/";
        public WordChecker()
        {
            httpClient = new HttpClient();
        }
        
        // an async method, make sure to call it with await!
        public async Task<bool> WordExists(string word)
        {
            var result = await httpClient.GetAsync(
            baseUrl + HttpUtility.UrlEncode(word));
            // if the word does not exist, the API will return a
            // 404 status code, resulting in this property to be false
            return result.IsSuccessStatusCode;
        }
        
        // make sure to call this method or use an using statement 
        // for the class
        public void Dispose()
        {
            httpClient.Dispose();
            GC.SuppressFinalize(this);
        }
    }

Now you can use this like following:

using (WordChecker checker)
{
    if (await checker.WordExists("my word")) 
    {
        Console.WriteLine("Word Exists!");
    }else
    {
        Console.WriteLine("Word does not exist.");
    }
}