/// <summary> /// guesses a language based on the entered word. It will always have an answer, however it might be wrong sometimes. /// it compares all words in all languages with the word and computes the relative difference. /// </summary> /// <param name="referenceWord"></param> /// <returns></returns> public Language GuessLanguage(string referenceWord) { if (Languages == null || string.IsNullOrWhiteSpace(referenceWord)) { return(null); } referenceWord = referenceWord.Trim().ToLower(); double mostMatchingSimilarity = 0; double s = 0; Language mostMatchingLanguage = Languages[0]; foreach (Language lan in Languages) { foreach (Word myWord in lan.Words) { s = SimilarityCalculator.CalculateSimilarity(referenceWord, myWord.Notation); if (s > mostMatchingSimilarity) { mostMatchingSimilarity = s; mostMatchingLanguage = lan; } } } return(mostMatchingLanguage); }
/// <summary> /// finds similar words of the same language /// </summary> /// <param name="word"></param> /// <param name="maxResultElements">the maximum length of the result array</param> /// <param name="minSimilarity">the minimum required similarity of the result words. 1.0d = must be same word, 0.0d = all words accepted</param> /// <returns>array of similar words or empty array if nothing was found</returns> public string[] FindSimilarWords(string word, int maxResultElements = 5, double minSimilarity = 0.2d) { if (string.IsNullOrWhiteSpace(word) || Words == null || Words.Length == 0 || maxResultElements < 1) { return(new string[0]); } // 1. calculate the amount of steps to transform one string into the other Dictionary <Word, double> wordTransformCosts = new Dictionary <Word, double>(); // go through the Words and look if one is similar and sort them by relevance. int WordCounter = 0; foreach (Word w in Words) { double similarity = SimilarityCalculator.CalculateSimilarity(word, w.Notation); if (similarity >= minSimilarity) // it should be at least 20% similar { wordTransformCosts.Add(w, similarity); WordCounter++; } if (WordCounter >= maxResultElements) // take 5 words at max. { break; } } string[] SimilarWords = new string[WordCounter]; // sort that dictionary, convert the words into the string array. int j = 0; foreach (KeyValuePair <Word, double> SortedWord in wordTransformCosts.OrderByDescending(key => key.Value)) { SimilarWords[j] = SortedWord.Key.Notation; j++; } return(SimilarWords); }