public static bool IsCommandSimilar(Command command, string notFoundCommand, NormalizedLevenshtein normalizedLevenshtein, double goodDistance = 0.33) { return(normalizedLevenshtein.Distance(command.Name, notFoundCommand) <= goodDistance || command?.Aliases?.Any(x => normalizedLevenshtein.Distance(x, notFoundCommand) <= goodDistance) == true || normalizedLevenshtein.Distance(command.QualifiedName, notFoundCommand) <= goodDistance); }
private void Button_Click(object sender, RoutedEventArgs e) { resultTexBox.Text = ""; progressBar.Value = 0; if (jaroWinklerCheckBox.IsChecked.Value) { Thread.Sleep(100); resultTexBox.Text += "\n\nJARO WINKLER:\nDistance = " + jw.Distance(textDoc1, textDoc2) + "\nSimilarity = " + jw.Similarity(textDoc1, textDoc2) * 100 + "%"; } progressBar.Value = 5; if (levenshteinCheckBox.IsChecked.Value) { Thread.Sleep(100); resultTexBox.Text += "\n\nLEVENSHTEIN:\nDistance = " + levenshtein.Distance(textDoc1, textDoc2); } progressBar.Value = 40; if (normalizedLevenshteinCheckBox.IsChecked.Value) { Thread.Sleep(100); resultTexBox.Text += "\n\nNORMALIZED LEVNSHTEIN:\nDistance = " + normalizedLevenshtein.Distance(textDoc1, textDoc2) + "\nSimilarity = " + normalizedLevenshtein.Similarity(textDoc1, textDoc2) * 100 + "%"; } progressBar.Value = 65; if (nGramCheckBox.IsChecked.Value) { Thread.Sleep(100); resultTexBox.Text += "\n\nNGRAM:\nDistance = " + nGram.Distance(textDoc1, textDoc2); } progressBar.Value = 100; }
private static SearchResult FindBestCandidateInFilteredResults(List <SearchResult> filteredResults, string rawCityNameLower) { var nameMatches = filteredResults.Where(r => r.Name.ToLowerInvariant() == rawCityNameLower).ToList <SearchResult>(); // Same name as rawCityNameLower if (nameMatches.Count > 0) { return(nameMatches[0]); } // StartsWith and Contains rawCityNameLower match var substringMatchPlaces = filteredResults.Where(r => r.Name.ToLowerInvariant().StartsWith(rawCityNameLower) || rawCityNameLower.StartsWith(r.Name.ToLowerInvariant()) || r.Name.ToLowerInvariant().Contains(rawCityNameLower) || rawCityNameLower.Contains(r.Name.ToLowerInvariant()) ).ToList <SearchResult>(); if (substringMatchPlaces.Count > 0) { return(substringMatchPlaces[0]); } // Normalized Levenshtein distance similarity match (similarity increases as score gets closer to 0) var similarNamePlaces = filteredResults.Where(r => nLevenshtein.Distance(r.Name.ToLowerInvariant(), rawCityNameLower) <= 0.2).ToList <SearchResult>(); if (similarNamePlaces.Count > 0) { return(similarNamePlaces[0]); } return(null); }
public static async Task CommandCorrector(string input, string command, string user = null, bool shouldBeExact = false) { // def variables IDictionary <Command, double> MatchRate = new Dictionary <Command, double>(); var Match = new NormalizedLevenshtein(); // filling array with matching rate for (int i = 0; i < Commands.List.Count; i++) { MatchRate.Add(Commands.List[i], Match.Distance(command, Commands.List[i].Key)); } //is there some rate lower than 35% if (!MatchRate.Any(q => q.Value <= 0.51d)) { await Respond("@" + input.ToLower().Split("!")[0].Replace(":", "") + " , Não entendi o seu comando, tente !Exclamação para obter a lista de todos os comandos..."); return; } else { //get the minimum match rate (closest command) var minimum = MatchRate.Min(q => q.Value); var arrayMinimum = MatchRate.Where(q => q.Value == minimum); if (arrayMinimum.Count() == 1) { if (shouldBeExact) { await Respond("@" + user + " , O comando " + command + " está incorreto; " + arrayMinimum.ElementAt(0).Key.Description); } else { var Tinput = input.ToLower().Split(command)[1]; var Tuser = input.ToLower().Split("!")[0].Replace(":", ""); await Respond("@" + Tuser + " , Seu commando foi corrigido para " + arrayMinimum.ElementAt(0).Key.Key + ", tente !Exclamação para obter a lista de todos os comandos..."); arrayMinimum.ElementAt(0).Key.Action.Invoke(Tinput, Tuser); } } else { string text = "@" + input.ToLower().Split("!")[0].Replace(":", "") + " , Não entendi o seu comando, não seria "; foreach (var item in arrayMinimum) { text += item.Key.Key + " ou "; } text += "tente !Exclamação para ver todos os comandos..."; await Respond(text); } } }
public async Task <string> Update() { var l = new NormalizedLevenshtein(); var staticVendors = _tmdb.PacingVendor.ToList().Select(i => i.Vendor).OrderBy(o => o).ToList(); var sDate = DateTime.Now.AddDays(-7); var eDate = DateTime.Now; var advVendors = (await Client.LoadMediaOrdersAsync(ServerName, DatabaseName, 0, UserName, Password, "A", sDate, sDate.Month, sDate.Year, eDate, eDate.Month, eDate.Year, true, false, false, false, false, false, "")).Select(i => i.VendorName).Distinct(); var res = advVendors.Where(s => !staticVendors.Any(e => { var ts = s.Replace(".com", "").Split("/")[0].ToLower(); var te = e.Replace(".com", "").Split("/")[0].ToLower(); return(l.Distance(ts, te) < 0.2 || ts.Contains(te) || te.Contains(ts)); })).OrderBy(o => o).ToList(); return("Span: Week\n" + string.Join('\n', res)); }
public async Task Check() { string userText = Stopwords.RemoveStopwords(AnsweredText); string ansText = Stopwords.RemoveStopwords(Question.Answer); var l = new NormalizedLevenshtein(); var similarity = 1 - l.Distance(userText, ansText); if (similarity >= 0.8) { UpdateBuzzCorrect(); } else { UpdateBuzzIncorrect(); } await UpdateAnswered(); }
private void MergeIntoDestination() { XmlNodeList nodes; var levenshtein = new NormalizedLevenshtein(); var root = _destDoc.DocumentElement; if (_replace) { nodes = root.SelectNodes("//xliff:trans-unit", _nsmgr); } else { nodes = root.SelectNodes("//xliff:trans-unit[not(xliff:target)]", _nsmgr); } foreach (XmlNode node in nodes) { var id = node.Attributes["id"].Value; if (_translations.ContainsKey(id)) { var source = node.SelectSingleNode("xliff:source", _nsmgr); var transSource = _translations[id].SelectSingleNode($"./xliff:source", _nsmgr); var transTarget = _translations[id].SelectSingleNode($"./xliff:target", _nsmgr); if (source.InnerText != transSource.InnerText) { var percentSimilar = Math.Round((1 - levenshtein.Distance(source.InnerText, transSource.InnerText)) * 100); if (_verbose) { Console.WriteLine($"Sources mismatch in id='{id}' Similarity {percentSimilar}%."); Console.WriteLine($" Source file='{transSource.InnerText}'"); Console.WriteLine($" Target file='{source.InnerText}'"); } if (percentSimilar < _fuzzy) { if (_verbose) { Console.WriteLine($"Skipping"); } continue; } } if (_replace) { var oldTarget = node.SelectSingleNode("xliff:target", _nsmgr); if (oldTarget != null) { node.RemoveChild(oldTarget); } } if (source.NextSibling.Name != "#significant-whitespace") { XmlSignificantWhitespace sigws = _destDoc.CreateSignificantWhitespace("\n "); node.InsertAfter(sigws, source); } XmlNode target = _destDoc.ImportNode(transTarget, true); node.InsertAfter(target, source.NextSibling); if (target.NextSibling.Name != "#significant-whitespace") { XmlSignificantWhitespace sigws = _destDoc.CreateSignificantWhitespace("\n "); node.InsertAfter(sigws, target); } } } }
public async Task PlayNext(CommandContext context, [RemainingText, Description("Название песни")] string songName) { if (string.IsNullOrWhiteSpace(songName)) { throw new DiscordUserInputException("Название песни не должно быть пустым", nameof(songName)); } var songs = new List <Songs>(); lock (this.Bot.UpdateMusicLock) { songs = this.Database.Playlist.ToList(); } var playNexts = new List <PlayNextElement>(); var nL = new NormalizedLevenshtein(); foreach (var song in songs) { playNexts.Add(new PlayNextElement(song.Path, song.Name, nL.Distance(song.Name, songName))); } playNexts = playNexts.OrderBy(s => s.Coefficient).ToList(); var interactivity = context.Client.GetInteractivity(); var description = new StringBuilder(); for (int i = 0; i < 10; i++) { description.AppendLine($"\n№ {i + 1}; Name: {playNexts[i].Title}."); } var listMsg = await context.RespondAsync(embed : EmbedTemplates.ExecutedByEmbed(context.Member, context.Guild.CurrentMember) .WithTitle("Предолагаемый список песен") .WithDescription(description.ToString()) .WithFooter($"Отправьте {Formatter.InlineCode("0")} для отмены")).ConfigureAwait(false); var msg = await interactivity.WaitForMessageAsync(xm => xm.Author.Id == context.User.Id, TimeSpan.FromSeconds(45)); if (!msg.TimedOut) { if (int.TryParse(msg.Result.Content, out int res)) { if (res >= 1 && res <= playNexts.Count) { var pNData = this.GuildMusic.MusicSources[(int)MusicSourceType.PlayNextData] as PlayNextData; pNData.Enqueue(playNexts[res - 1].PathToFile); await listMsg.ModifyAsync(embed : EmbedTemplates.ExecutedByEmbed(context.Member, context.Guild.CurrentMember) .WithTitle($"Следующей песней будет {playNexts[res - 1].Title}").Build()).ConfigureAwait(false); } else if (res == 0) { await listMsg.ModifyAsync("Выбор отменен", null).ConfigureAwait(false); } else { await listMsg.ModifyAsync("Данное число выходит за границы", null).ConfigureAwait(false); } } else { await listMsg.ModifyAsync("Ответ не является числом или время вышло", null).ConfigureAwait(false); } } await Task.Delay(TimeSpan.FromSeconds(30)); await listMsg.DeleteAsync(); }
public async Task ExecuteGroup(CommandContext context, [RemainingText, Description("Название тега для отображения")] string name) { if (string.IsNullOrWhiteSpace(name) || ForbiddenNames.Contains(name.ToLower())) { throw new DiscordUserInputException("Название тега не может быть пустым, полностью состоять из пробелов или быть называться также как и команды.", nameof(name)); } var gId = (long)context.Guild.Id; var tag = await this.Database.Tags.SingleOrDefaultAsync(t => t.Name == name && t.GuildId == gId).ConfigureAwait(false); if (tag == null) { var nL = new NormalizedLevenshtein(); var tags = await this.Database.Tags.Where(t => t.GuildId == gId).OrderBy(t => nL.Distance(t.Name, name)).ToArrayAsync().ConfigureAwait(false); if (tags?.Any() == false) { throw new DiscordUserInputException("Тегов на этом сервере не найдено", nameof(tags)); } string suggestions = (tags.Length >= 10 ? string.Join(", ", tags.Take(10).OrderBy(x => x.Name).Select(xt => Formatter.InlineCode(xt.Name)).Distinct()) : string.Join(", ", tags.OrderBy(x => x.Name).Select(xt => Formatter.InlineCode(xt.Name)).Distinct())); await context.RespondAsync($"Нужного тега не найдено, вот некоторые {Formatter.Italic("возможные варианты того что вы искали")}:\n\u200b{suggestions}").ConfigureAwait(false); } else { string content = tag.TagContent.Replace("@here", "@\u200bhere").Replace("@everyone", "@\u200beveryone").Trim(); await context.RespondAsync($"\u200b{content}").ConfigureAwait(false); tag.TimesUsed++; this.Database.Tags.Update(tag); int rowsAffected = await this.Database.SaveChangesAsync(); if (rowsAffected <= 0) { throw new DatabaseException("Не удалось обновить количество использований в базе данных", DatabaseActionType.Save); } } }