public static AnalysisResult Process(string text) { Stopwatch timer = new Stopwatch(); timer.Start(); Processor processor = ProcessorService.CreateProcessor(); // cached var result = processor.Process(new SourceOfAnalysis(text)); timer.Stop(); TimeSpan span = timer.Elapsed; string time = String.Format("{0}.{1:000}", span.Seconds, span.Milliseconds); int size = text.Length; int referents = result.Entities.Count; Log.Info("Process: {0} chars, {1}s, {2} refs", size, time, referents); return(result); }
private string GetPersonName() { var paragraphs = Document.Descendants <Paragraph>().ToList(); string txt = FindTitleAboveTheTable(); // создаём экземпляр обычного процессора using (Processor proc = ProcessorService.CreateProcessor()) { // анализируем текст AnalysisResult ar = proc.Process(new SourceOfAnalysis(txt)); var nameEntity = ar.Entities.ToList().Find(x => x.TypeName == "PERSON"); if (nameEntity != default) { var t = nameEntity.ToString().Split(" "); return($"{t[2]} {t[0]} {t[1]}"); } } return(default);
/* * private static void FillLists(List<Referent> entities) * { * foreach(var e in entities) * { * listNamedEntities.Add(new NamedEntity(e, e.Slots * .Select(t => new NamedEntityElement(t.TypeName, t.Value.ToString())).ToArray())); * } * } */ private static Processor InitializeProcessor() { Sdk.Initialize(MorphLang.RU); var proc = ProcessorService.CreateProcessor(); // баганутый proc.AddAnalyzer(new Pullenti.Ner.Measure.MeasureAnalyzer()); return(proc); /* * Для пустого процессора * * processor.AddAnalyzer(new Pullenti.Ner.Address.AddressAnalyzer()); * processor.AddAnalyzer(new Pullenti.Ner.Date.DateAnalyzer()); * processor.AddAnalyzer(new Pullenti.Ner.Money.MoneyAnalyzer()); * processor.AddAnalyzer(new Pullenti.Ner.Named.NamedEntityAnalyzer()); * processor.AddAnalyzer(new Pullenti.Ner.Person.PersonAnalyzer()); * processor.AddAnalyzer(new Pullenti.Ner.Phone.PhoneAnalyzer()); * processor.AddAnalyzer(new Pullenti.Ner.Measure.MeasureAnalyzer()); */ }
void crawler_ProcessPageCrawlCompleted(object sender, PageCrawlCompletedArgs e) { CrawledPage crawledPage = e.CrawledPage; string uri = crawledPage.Uri.AbsoluteUri; if (crawledPage.WebException != null || crawledPage.HttpWebResponse.StatusCode != HttpStatusCode.OK) { new HelloResponse { Result = $"Crawl of page failed {uri}!" } } ; else { new HelloResponse { Result = $"Crawl of page succeeded {uri}!" } }; var htmlAgilityPackDocument = crawledPage.HtmlDocument; //Html Agility Pack parser Extract(e, htmlAgilityPackDocument); } string RemoveQuotes(string articleText) { return(Regex.Replace(articleText, "\"", String.Empty)); } void Extract(PageCrawlCompletedArgs page, HtmlDocument htmlAgilityPackDocument) { try { DateTime date = default(DateTime); string entityText = ""; StringBuilder text = new StringBuilder(); StringBuilder headerArticle = new StringBuilder(); StringBuilder articleText = new StringBuilder(); var t2 = htmlAgilityPackDocument.DocumentNode.SelectSingleNode("//div[@class='news-detail']"); if (t2 != null) { // You need to add an * to the xpath. The * means you want to select any element. // With an xpath query you can also use "." to indicate the search should start at the current node. HtmlNode HeaderArticleNode = t2.SelectSingleNode(".//*[@class='name']"); if (HeaderArticleNode != null) { headerArticle.Append(RemoveQuotes(HeaderArticleNode.InnerText)); } HtmlNode TextNode = t2.SelectSingleNode(".//*[@id='detailText']"); if (TextNode != null) { if (TextNode.InnerText != "") { articleText.Append(RemoveQuotes(TextNode.InnerText)); ProcessorService.Initialize(MorphLang.RU | MorphLang.EN); EP.Ner.Geo.GeoAnalyzer.Initialize(); EP.Ner.Org.OrganizationAnalyzer.Initialize(); EP.Ner.Person.PersonAnalyzer.Initialize(); //// создаём экземпляр обычного процессора using (Processor proc = ProcessorService.CreateProcessor()) { // анализируем текст AnalysisResult ar = proc.Process(new SourceOfAnalysis(articleText.ToString().Trim())); // результирующие сущности foreach (var e in ar.Entities) { // if (e.GetType().Name.Equals("GeoReferent")) //e.GetType().Name + " " + e; entityText += e.ToString() + " "; } } } } /* * // Вариант с перебором всех дочерних узлов и использованием Descendants * HtmlNodeCollection childNodes = t2.ChildNodes; * foreach (var nNode in childNodes.Descendants("h1")) * { * if (nNode.NodeType == HtmlNodeType.Element) * { * name = nNode.InnerText; * } * } */ } htmlAgilityPackDocument.DocumentNode.SelectNodes("//style|//script").ToList().ForEach(n => n.Remove()); var xpath = "//text()[not(normalize-space())]"; var emptyNodes = htmlAgilityPackDocument.DocumentNode.SelectNodes(xpath); //replace each and all empty text nodes with single new-line text node foreach (HtmlNode emptyNode in emptyNodes) { emptyNode.ParentNode .ReplaceChild(HtmlTextNode.CreateNode(Environment.NewLine) , emptyNode ); } string FullText = htmlAgilityPackDocument.DocumentNode.InnerHtml.AsString(); var bla = htmlAgilityPackDocument.DocumentNode.SelectSingleNode("//span[@class='news-date-time news_date']"); if (bla != null) { bla.InnerHtml.ToString(); date = DateTime.Parse(bla.InnerText); } if (headerArticle.Length != 0 & articleText.Length != 0) { using (var db = dbConnectionFactory.OpenDbConnection()) { db.Insert(new Article() { // HeaderArticle = HeaderArticle, HeaderArticle = headerArticle.ToString().Trim(), UrlArticle = page.CrawledPage.Uri.AbsoluteUri, FullText = page.CrawledPage.HtmlDocument.DocumentNode.OuterHtml, Text = articleText.ToString().Trim(), LastUpdated = date, EntityText = entityText, } ); } } } catch (Exception e) { Console.WriteLine("", e.Message); } } }
static void Main(string[] args) { Stopwatch sw = Stopwatch.StartNew(); // инициализация - необходимо проводить один раз до обработки текстов Console.Write("Initializing ... "); ProcessorService.Initialize(MorphLang.RU | MorphLang.EN); // инициализируются все используемые анализаторы //EP.Ner.Money.MoneyAnalyzer.Initialize(); //EP.Ner.Uri.UriAnalyzer.Initialize(); //EP.Ner.Phone.PhoneAnalyzer.Initialize(); //EP.Ner.Definition.DefinitionAnalyzer.Initialize(); //EP.Ner.Date.DateAnalyzer.Initialize(); //EP.Ner.Bank.BankAnalyzer.Initialize(); EP.Ner.Geo.GeoAnalyzer.Initialize(); // этот нужен // EP.Ner.Address.AddressAnalyzer.Initialize(); EP.Ner.Org.OrganizationAnalyzer.Initialize(); // Этот нужен EP.Ner.Person.PersonAnalyzer.Initialize(); // этот нужен //EP.Ner.Mail.MailAnalyzer.Initialize(); //EP.Ner.Transport.TransportAnalyzer.Initialize(); //EP.Ner.Decree.DecreeAnalyzer.Initialize(); //EP.Ner.Titlepage.TitlePageAnalyzer.Initialize(); //EP.Ner.Booklink.BookLinkAnalyzer.Initialize(); //EP.Ner.Named.NamedEntityAnalyzer.Initialize(); //EP.Ner.Goods.GoodsAnalyzer.Initialize(); sw.Stop(); Console.WriteLine("OK (by {0} ms), version {1}", (int)sw.ElapsedMilliseconds, ProcessorService.Version); // анализируемый текст string txt = " улица Куйбышева Единственным конкурентом «Трансмаша» на этом дебильном тендере фамилия Гуполович было ООО «Плассер Алека Рейл Сервис», основным владельцем которого является австрийская компания «СТЦ-Холдинг ГМБХ». До конца 2011 г. эта же фирма была совладельцем «Трансмаша» вместе с «Тако» Краснова. Зато совладельцем «Плассера», также до конца 2011 г., был тот самый Карл Контрус, который имеет четверть акций «Трансмаша». "; // создаём экземпляр обычного процессора using (Processor proc = ProcessorService.CreateProcessor()) { // анализируем текст AnalysisResult ar = proc.Process(new SourceOfAnalysis(txt)); // результирующие сущности Console.WriteLine("Entities: "); foreach (var e in ar.Entities) { if (e.GetType().Name.Equals("GeoReferent")) { Console.WriteLine(e.GetType().Name + " " + e + " if прошел успешно"); } else { Console.WriteLine(e.GetType().Name + " " + e); } } //// пример выделения именных групп //Console.WriteLine("Noun groups: "); //for (Token t = ar.FirstToken; t != null; t = t.Next) //{ // if (t.GetReferent() != null) continue; // токены с сущностями игнорируем // // пробуем создать именную группу // NounPhraseToken npt = NounPhraseHelper.TryParse(t, NounPhraseParseAttr.AdjectiveCanBeLast); // if (npt == null) continue; // не получилось // Console.WriteLine(npt); // t = npt.EndToken; // указатель на последний токен группы //} } Console.WriteLine("Over!"); }