public ActionResult Phrase(string w) { ViewBag.Page = "Decline.Phrase"; if (string.IsNullOrEmpty(w)) { return(View()); } List <string> errors = new List <string>(); CyrPhrase phrase = new CyrPhrase(this.NounCollection, this.AdjectiveCollection); CyrResult singular = null; CyrResult plural = null; try { singular = phrase.Decline(w, GetConditionsEnum.Similar); plural = phrase.DeclinePlural(w, GetConditionsEnum.Similar); } catch (CyrWordNotFoundException ex) { errors.Add(string.Format("Слово \"<strong>{0}</strong>\" не найдено в коллекции. Попбробуйте убрать слово из фразы.", ex.Word)); return(View()); } ViewBag.Text = w; ViewBag.Errors = errors; ViewBag.Singular = singular; ViewBag.Plural = plural; ViewBag.Cases = CyrDeclineCase.GetEnumerable().ToArray(); return(View()); }
private void btnDecline_Click(object sender, EventArgs e) { if (txtWord.Text.IsNullOrEmpty()) { MessageBox.Show("Необходимо ввести слово или фразу!"); } CyrPhrase phrase = new CyrPhrase(nounCollection, adjCollection); CyrResult result; try { if (ddlAction.SelectedIndex == 0) { result = phrase.Decline(txtWord.Text, GetConditionsEnum.Similar); } else { result = phrase.DeclinePlural(txtWord.Text, GetConditionsEnum.Similar); } } catch (CyrWordNotFoundException ex) { MessageBox.Show(string.Format("Слово {0} не найдено в коллекции!", ex.Word)); return; } this.SetResult(result); }
public string DeclinePhraseInPlural(string words, string caseName = "Nominative") { var phrase = new CyrPhrase(nouns, adjs); var declineRes = phrase.DeclinePlural(words, GetConditionsEnum.Similar); return(GetDeclensionInCase(declineRes, caseName)); }
private void btnDecline_Click(object sender, EventArgs e) { if (txtWord.Text.IsNullOrEmpty()) { MessageBox.Show("Необходимо ввести слово или фразу!"); } CyrPhrase phrase = new CyrPhrase(nounCollection, adjCollection); CyrResult result; try { if (ddlAction.SelectedIndex == 0) { result = phrase.Decline(txtWord.Text, GetConditionsEnum.Similar); } else { result = phrase.DeclinePlural(txtWord.Text, GetConditionsEnum.Similar); } } catch (CyrWordNotFoundException ex) { MessageBox.Show(string.Format("Слово {0} не найдено в коллекции!", ex.Word)); return; } this.SetResult(result); }
public static List <string> GetPhraseDeclension(string phrase) { var singular = _cyrPhraseCollection.Decline(phrase, GetConditionsEnum.Strict).ToArray(); var plural = _cyrPhraseCollection.DeclinePlural(phrase, GetConditionsEnum.Strict).ToArray(); var result = new List <string>(); result.AddRange(singular.Where(singularWord => !string.IsNullOrEmpty(singularWord))); result.AddRange(plural.Where(singularWord => !string.IsNullOrEmpty(singularWord))); return(result.Distinct().ToList()); }
public ActionResult List(string w) { ViewBag.Page = "Decline.List"; if (w.IsNullOrEmpty()) { return(View()); } string[] items = w.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (!items.Any()) { return(View()); } List <CyrResult> singulars = new List <CyrResult>(); List <CyrResult> plurals = new List <CyrResult>(); List <string> errors = new List <string>(); if (items.Length > MaxPhrasesToDecline) { errors.Add($"За один раз можно склонять максимум {MaxPhrasesToDecline} фраз!"); } for (int i = 0; i < items.Length && i < MaxPhrasesToDecline; i++) { string item = items[i]; CyrPhrase phrase = new CyrPhrase(this.NounCollection, this.AdjectiveCollection); CyrResult singular = null; CyrResult plural = null; try { singular = phrase.Decline(item, GetConditionsEnum.Similar); plural = phrase.DeclinePlural(item, GetConditionsEnum.Similar); } catch (CyrWordNotFoundException ex) { errors.Add(string.Format("Слово \"<strong>{0}</strong>\" не найдено в коллекции. Попбробуйте убрать слово из фразы.", ex.Word)); continue; } singulars.Add(singular); plurals.Add(plural); } ViewBag.Text = w; ViewBag.Errors = errors; ViewBag.Singulars = singulars; ViewBag.Plurals = plurals; ViewBag.Cases = CyrDeclineCase.GetEnumerable().ToArray(); return(View()); }
public static CyrResult DeclinePlural(CyrPhrase decliner, string phrase) { try { return(decliner.DeclinePlural(phrase, GetConditionsEnum.Strict)); } catch { return(null); } }
protected void DeclineTextFile(HttpPostedFileBase File, bool Plural) { string name = Guid.NewGuid() + ".txt"; string path = Path.Combine(TempFolder, name); CyrDeclineCase[] cases = CyrDeclineCase.GetEnumerable().ToArray(); CyrPhrase phrase = new CyrPhrase(NounCollection, AdjectiveCollection); TextReader reader = new StreamReader(File.InputStream, true); TextWriter writer = new StreamWriter(path, false, System.Text.Encoding.UTF8); string line = reader.ReadLine(); int totalPhrases = 0; int errorPhrases = 0; for (int i = 0; i < cases.Length; i++) { if (i > 0) { writer.Write(" | "); } writer.Write(cases[i].NameRu); writer.Write(" "); writer.Write(cases[i].Description); } while (line.IsNotNullOrEmpty()) { totalPhrases++; try { CyrResult result; if (Plural) { result = phrase.DeclinePlural(line, GetConditionsEnum.Similar); } else { result = phrase.Decline(line, GetConditionsEnum.Similar); } writer.Write(Environment.NewLine); for (int i = 0; i < cases.Length; i++) { if (i > 0) { writer.Write(" | "); } writer.Write(result[cases[i].Index]); } } catch (CyrWordNotFoundException ex) { writer.Write(Environment.NewLine); writer.Write(string.Format("Слово \"{0}\" не найдено в коллекции. Попбробуйте убрать слово из фразы.", ex.Word)); errorPhrases++; } line = reader.ReadLine(); } reader.Dispose(); writer.Close(); writer.Dispose(); ViewBag.DownloadFileName = name; ViewBag.TotalPhrases = totalPhrases; ViewBag.ErrorPhrases = errorPhrases; }
protected void DeclineExcelFile(HttpPostedFileBase File, bool Plural) { ExcelPackage package; try { package = new ExcelPackage(File.InputStream); } catch { ViewBag.Errors = new string[] { $"Не удается открыть {File.FileName} файл, возможно файл поврежден или не является правильным документом Microsoft Excel." }; return; } string name = Guid.NewGuid() + ".xlsx"; string path = Path.Combine(TempFolder, name); CyrDeclineCase[] cases = CyrDeclineCase.GetEnumerable().ToArray(); CyrPhrase phrase = new CyrPhrase(NounCollection, AdjectiveCollection); ExcelWorksheet input = package.Workbook.Worksheets[1]; ExcelWorksheet output = package.Workbook.Worksheets.Add("Результат"); int rowIndex = 1; string line = input.Cells[rowIndex, 1].Value?.ToString(); int totalPhrases = 0; int errorPhrases = 0; foreach (CyrDeclineCase dc in cases) { output.Cells[rowIndex, dc.Index].Value = $"{dc.NameRu}, {dc.Description}"; } while (line.IsNotNullOrEmpty()) { rowIndex++; totalPhrases++; try { CyrResult result; if (Plural) { result = phrase.DeclinePlural(line, GetConditionsEnum.Similar); } else { result = phrase.Decline(line, GetConditionsEnum.Similar); } foreach (CyrDeclineCase dc in cases) { output.Cells[rowIndex, dc.Index].Value = result[dc.Index]; } } catch (CyrWordNotFoundException ex) { output.Cells[rowIndex, 1].Value = string.Format("Слово \"{0}\" не найдено в коллекции. Попбробуйте убрать слово из фразы.", ex.Word); errorPhrases++; } line = input.Cells[rowIndex, 1].Value?.ToString(); } output.Cells.AutoFitColumns(); package.SaveAs(new FileInfo(path)); package.Dispose(); ViewBag.DownloadFileName = name; ViewBag.TotalPhrases = totalPhrases; ViewBag.ErrorPhrases = errorPhrases; }
public ActionResult Phrase(string w) { ViewBag.Page = "Decline.Phrase"; if (string.IsNullOrEmpty(w)) { return View(); } List<string> errors = new List<string>(); CyrPhrase phrase = new CyrPhrase(this.NounCollection, this.AdjectiveCollection); CyrResult singular = null; CyrResult plural = null; try { singular = phrase.Decline(w, GetConditionsEnum.Similar); plural = phrase.DeclinePlural(w, GetConditionsEnum.Similar); } catch (CyrWordNotFoundException ex) { errors.Add(string.Format("Слово \"<strong>{0}</strong>\" не найдено в коллекции. Попбробуйте убрать слово из фразы.", ex.Word)); return View(); } ViewBag.Text = w; ViewBag.Errors = errors; ViewBag.Singular = singular; ViewBag.Plural = plural; return View(); }
#pragma warning disable IDE0060 // Удалите неиспользуемый параметр private static void Main(string[] args) #pragma warning restore IDE0060 // Удалите неиспользуемый параметр { var logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Console() .WriteTo.File("logs\\foodbot.txt", rollingInterval: RollingInterval.Day) .CreateLogger(); IConfiguration configuration = new ConfigurationBuilder() .AddJsonFile("appsettings.json", true, true) .AddJsonFile("food.json", true, true) .AddJsonFile("vk.json", true, true) .Build(); //собираем беседы в контейнер var collection = new ServiceCollection(); Assembly ConsoleAppAssembly = typeof(Program).Assembly; var ConsoleAppTypes = from type in ConsoleAppAssembly.GetTypes() where !type.IsAbstract where typeof(IConversation).IsAssignableFrom(type) select type; foreach (var type in ConsoleAppTypes) { collection.AddTransient(typeof(IConversation), type); } var conf = new Dictionary <Categories, List <string> >(); configuration.GetSection("Categories").Bind(conf); var cyrPhrase = new CyrPhrase(new CyrNounCollection(), new CyrAdjectiveCollection()); var foodDictionary = new Dictionary <Categories, List <string> >(); foreach (KeyValuePair <Categories, List <string> > cat in conf) { var l = new List <string>(); foreach (var food in cat.Value) { var s = cyrPhrase.Decline(food.ToLower(), Cyriller.Model.GetConditionsEnum.Similar).ToList(); var p = cyrPhrase.DeclinePlural(food.ToLower(), Cyriller.Model.GetConditionsEnum.Similar).ToList(); l.AddRange(s.Union(p).Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList()); } foodDictionary.Add(cat.Key, l); } cyrPhrase = null; var client = new TelegramBotClient(configuration["BotKey"]); collection.AddSingleton <BotEngine>(); collection.AddSingleton(client); collection.AddSingleton(configuration); collection.AddTransient <IJob, ParseVkJob>(); collection.AddTransient <StateRepository>(); collection.AddTransient <NoticeRepository>(); collection.AddTransient <VkParser>(); collection.AddSingleton(foodDictionary); collection.AddSingleton <ILogger>(logger); collection.AddTransient <Categorizer>(); collection.AddTransient <Geocoding>(); var serviceProvider = collection.BuildServiceProvider(); // on-start self-check var me = client.GetMeAsync().Result; Console.WriteLine( $"Hello! I am user {me.Id} and my name is {me.FirstName}." ); // регистрируем движок и вешаем события BotEngine engine = serviceProvider.GetService <BotEngine>(); client.OnMessage += engine.BotOnMessageReceived; client.OnReceiveError += engine.BotOnReceiveError; client.OnInlineQuery += engine.BotOnInlineQuery; client.OnCallbackQuery += engine.BotOnCallbackQuery; // endless background job Thread workerThread = new Thread(async() => { while (true) { var jobs = serviceProvider.GetServices <IJob>().ToList(); foreach (IJob j in jobs) { try { await j.Execute(); } catch (Exception ex) { logger.Error("{@ex}", ex); } } ; Thread.Sleep(int.Parse(configuration["JobSleepTimer"])); } }); workerThread.Start(); client.StartReceiving(); Console.ReadLine(); client.StopReceiving(); }