/// <summary> /// Parses the specified <see cref="ISentence"/> object using a given <paramref name="parser"/>. /// </summary> /// <param name="sentence">The sentence to be parsed.</param> /// <param name="parser">The parser.</param> /// <param name="numParses">The number parses. Usually 1.</param> /// <returns>An array with the parsed results.</returns> /// <exception cref="System.ArgumentNullException"> /// <paramref name="sentence"/> /// or /// <paramref name="parser"/> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException">numParses</exception> /// <exception cref="System.InvalidOperationException">The sentence is not tokenized.</exception> public static Parse[] ParseLine(ISentence sentence, IParser parser, int numParses) { if (sentence == null) throw new ArgumentNullException("sentence"); if (parser == null) throw new ArgumentNullException("parser"); if (numParses < 0) throw new ArgumentOutOfRangeException("numParses"); if (sentence.Tokens == null || sentence.Tokens.Count == 0) throw new InvalidOperationException("The sentence is not tokenized."); var sb = new StringBuilder(sentence.Length); for (var i = 0; i < sentence.Tokens.Count; i++) { sb.Append(sentence.Tokens[i].Lexeme).Append(' '); } sb.Remove(sb.Length - 1, 1); var start = 0; var p = new Parse(sb.ToString(), new Span(0, sb.Length), AbstractBottomUpParser.INC_NODE, 0, 0); for (var i = 0; i < sentence.Tokens.Count; i++) { p.Insert( new Parse( sb.ToString(), new Span(start, start + sentence.Tokens[i].Lexeme.Length), AbstractBottomUpParser.TOK_NODE, 0, i)); start += sentence.Tokens[i].Lexeme.Length + 1; } return numParses == 1 ? new[] { parser.Parse(p) } : parser.Parse(p, numParses); }
public CreateNTriplesPrefixTarget(NTriplesPrefixReference reference) { this.myElement = reference.GetTreeNode(); string name = reference.GetName(); var uri = this.TryFindUri(reference); this.myDeclaration = NTriplesElementFactory.GetInstance(this.myElement.GetPsiModule()).CreatePrefixDeclarationSentence(name, uri); this.Anchor = this.FindAnchor(); }
public Literal CreateAnswerLiteral(ISentence forQuery) { string alName = parser.GetFOLDomain().AddAnswerLiteral(); IList <ITerm> terms = new List <ITerm>(); ISet <Variable> vars = variableCollector.CollectAllVariables(forQuery); foreach (Variable v in vars) { // Ensure copies of the variables are used. terms.Add((ITerm)v.Copy()); } return(new Literal(new Predicate(alName, terms))); }
/// <summary> /// Gets the part-of-speech tags from the <see cref="ISentence"/> object. /// </summary> /// <param name="sentence">The sentence.</param> /// <returns>A string array containing the tokens or a <c>null</c> value if the tokens are not available.</returns> /// <exception cref="System.ArgumentNullException">sentence</exception> public static string[] GetTags(this ISentence sentence) { if (sentence == null) { throw new ArgumentNullException(nameof(sentence)); } if (sentence.Tokens == null || sentence.TagProbability.Equals(0d)) { return(null); } return(sentence.Tokens != null ? sentence.Tokens.Select(token => token.POSTag).ToArray() : null); }
public IInferenceResult Ask(FOLKnowledgeBase kb, ISentence aQuery) { // // Get the background knowledge - are assuming this is satisfiable // as using Set of Support strategy. ISet <Clause> bgClauses = new HashedSet <Clause>(kb.GetAllClauses()); bgClauses.ExceptWith(SubsumptionElimination.FindSubsumedClauses(bgClauses)); IList <Chain> background = CreateChainsFromClauses(bgClauses); // Collect the information necessary for constructing // an answer (supports use of answer literals). var ansHandler = new AnswerHandler(kb, aQuery, this.MaxQueryTime); var ifps = new IndexedFarParents(ansHandler .GetSetOfSupport(), background); // Iterative deepening to be used for (int maxDepth = 1; maxDepth < int.MaxValue; maxDepth++) { // Track the depth actually reached ansHandler.ResetMaxDepthReached(); if (null != tracer) { tracer.Reset(); } foreach (Chain nearParent in ansHandler.GetSetOfSupport()) { this.RecursiveDls(maxDepth, 0, nearParent, ifps, ansHandler); if (ansHandler.IsComplete()) { return(ansHandler); } } // This means the search tree // has bottomed out (i.e. finite). // Return what I know based on exploring everything. if (ansHandler.GetMaxDepthReached() < maxDepth) { return(ansHandler); } } return(ansHandler); }
public static Substitution Unify(ISentence sentence1, ISentence sentence2) { var res = new Substitution(); res.Successful = false; switch (sentence1.GetSentenceType()) { case SentenceType.Predicate: if (sentence2.GetSentenceType() == SentenceType.QuantifierVariableSentence) { var qvs2 = sentence2 as QuantifierVariableSentence; if (qvs2.Quantifier != Quantifier.Exists) { break; } return(Unify(sentence1, qvs2.Sentence)); } if (sentence2.GetSentenceType() == SentenceType.SentenceConnectiveSentence) { break; } var pred1 = sentence1 as Predicate; var pred2 = sentence2 as Predicate; return(PredicateUnify(pred1, pred2)); case SentenceType.SentenceConnectiveSentence: if (sentence1.GetSentenceType() != sentence2.GetSentenceType()) { break; } var scs1 = sentence1 as SentenceConnectiveSentence; var scs2 = sentence1 as SentenceConnectiveSentence; return(Unify(scs1.Sentence1, scs2.Sentence1).Compose(Unify(scs1.Sentence2, scs2.Sentence2))); case SentenceType.QuantifierVariableSentence: var qvs1 = sentence1 as QuantifierVariableSentence; if (qvs1.Quantifier == Quantifier.Exists) { return(Unify(qvs1.Sentence, sentence2)); } break; default: return(res); } return(res); }
public static bool IsRenaiming(ISentence sentence1, ISentence sentence2) { var unification = Unify(sentence1, sentence2); if (!unification.Successful) { return(false); } foreach (var val in unification.SubsitutionDict.Values) { if (Char.IsUpper(val[0])) { return(false); } } return(true); }
//4. В некотором предложении текста слова заданной длины заменить указанной подстрокой, длина которой может не совпадать с длиной слова. public static ISentence ReplaceWordBySubstring(ISentence sentence, int length, string newSubstring) { length = ValidateLength(length); newSubstring = ValidateString(newSubstring); IList <ISentenceItem> substring = new MyParser().ParseSentence(newSubstring); ISentence changedSentence = sentence; for (int i = 0; i < sentence.Items.Count; i++) { if (changedSentence.Items[i] is Word && changedSentence.Items[i].Length == length) { changedSentence.ReplaceWord(changedSentence.Items[i] as Word, substring); } } return(changedSentence); }
/// <summary> /// Parses the specified <see cref="ISentence"/> object using a given <paramref name="parser"/>. /// </summary> /// <param name="sentence">The sentence to be parsed.</param> /// <param name="parser">The parser.</param> /// <param name="numParses">The number parses. Usually 1.</param> /// <returns>An array with the parsed results.</returns> /// <exception cref="System.ArgumentNullException"> /// <paramref name="sentence"/> /// or /// <paramref name="parser"/> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException">numParses</exception> /// <exception cref="System.InvalidOperationException">The sentence is not tokenized.</exception> public static Parse[] ParseLine(ISentence sentence, IParser parser, int numParses) { if (sentence == null) { throw new ArgumentNullException(nameof(sentence)); } if (parser == null) { throw new ArgumentNullException(nameof(parser)); } if (numParses < 0) { throw new ArgumentOutOfRangeException(nameof(numParses)); } if (sentence.Tokens == null || sentence.Tokens.Count == 0) { throw new InvalidOperationException("The sentence is not tokenized."); } var sb = new StringBuilder(sentence.Length); for (var i = 0; i < sentence.Tokens.Count; i++) { sb.Append(sentence.Tokens[i].Lexeme).Append(' '); } sb.Remove(sb.Length - 1, 1); var start = 0; var p = new Parse(sb.ToString(), new Span(0, sb.Length), AbstractBottomUpParser.INC_NODE, 0, 0); for (var i = 0; i < sentence.Tokens.Count; i++) { p.Insert( new Parse( sb.ToString(), new Span(start, start + sentence.Tokens[i].Lexeme.Length), AbstractBottomUpParser.TOK_NODE, 0, i)); start += sentence.Tokens[i].Lexeme.Length + 1; } return(numParses == 1 ? new[] { parser.Parse(p) } : parser.Parse(p, numParses)); }
private void Store(ISentence aSentence) { originalSentences.Add(aSentence); // Convert the sentence to CNF CNF cnfOfOrig = cnfConverter.ConvertToCNF(aSentence); foreach (Clause c in cnfOfOrig.GetConjunctionOfClauses()) { c.SetProofStep(new ProofStepClauseClausifySentence(c, aSentence)); if (c.IsEmpty()) { // This should not happen, if so the user // is trying to add an unsatisfiable sentence // to the KB. throw new InvalidOperationException( "Attempted to add unsatisfiable sentence to KB, orig=[" + aSentence + "] CNF=" + cnfOfOrig); } // Ensure all clauses added to the KB are Standardized Apart. var standardizedC = standardizeApart.GetStandardizeApartResult(c, variableIndexical); // Will make all clauses immutable // so that they cannot be modified externally. standardizedC.Immutable = true; if (clauses.Add(standardizedC)) { // If added keep track of special types of // clauses, as useful for query purposes if (standardizedC.IsDefiniteClause()) { allDefiniteClauses.Add(standardizedC); } if (standardizedC.IsImplicationDefiniteClause()) { implicationDefiniteClauses.Add(standardizedC); } if (standardizedC.IsUnitClause()) { this.IndexFact(standardizedC.GetLiterals().First()); } } } }
public static void RemoveWordsFirstConsonantLetter(this IText text, int length) { TokenLetter alphabet = new TokenLetter(); for (int i = 0; i < text.Sentences.Count; ++i) { ISentence sentence = text.Sentences[i]; var wordsForDelete = sentence .GetWords() .Where(x => x.Length == length && alphabet.IsLetter(x) && alphabet.GetSound(x) == TypeLetter.Consonant ).ToList(); wordsForDelete.ForEach(x => sentence.Remove(x)); } }
public ISentence ReplaceWordOnSubstring(ISentence sentence, int length, string subString) { var count = sentence.Items.Count; for (var i = 0; i < count; i++) { if (sentence.Items[i].Chars.Length != length) { continue; } var index = sentence.Items.IndexOf(sentence.Items[i]); sentence.Items.RemoveAt(index); var word = new Word(subString); sentence.Items.Insert(index, word); } return(sentence); }
public ISentence ParseSentenceByItems(string stringSentence) { int separatorIndex = -1; StringBuilder buffer_1 = new StringBuilder(); StringBuilder buffer_2 = new StringBuilder(); buffer_1.Append(stringSentence.Trim()); while (buffer_1.Length != 0) { string wordSeparator = " "; string word = GetSentenceItems(ref separatorIndex, ref wordSeparator, symbolContainer.AllSeparators, buffer_1.ToString()); if (word != "") { sentenceCreator.Add(new Space(new Symbol(' '))); sentenceCreator.Add(wordCreator.Create(word)); } if (wordSeparator != " ") { sentenceCreator.Add(new Punctuation(new Symbol(wordSeparator))); } buffer_2.Append(buffer_1); buffer_1.Clear(); buffer_1.Append(buffer_2.ToString(). Substring( separatorIndex + wordSeparator.Length, buffer_2.Length - separatorIndex - wordSeparator.Length). Trim()); if (string.Compare(buffer_1.ToString(), buffer_2.ToString()) != 0) { buffer_2.Clear(); } else { buffer_1.Clear(); buffer_2.Clear(); } } ISentence sentence = sentenceCreator.Create(); sentenceCreator.Clear(); return(sentence); }
/// <summary> /// Выдаёт словарь клауз и их отношений для всего предложения /// </summary> /// <param name="sentence">Предложение</param> /// <param name="bestVariantsNombers">варианты предложений</param> /// <returns>список отношений для всего предложения</returns> private Dictionary <int, List <IRelation> > getRelationsDict(ISentence sentence, int[] bestVariantsNombers) { Dictionary <int, List <IRelation> > relations = new Dictionary <int, List <IRelation> >(); IRelationsIterator relationsIterator = sentence.CreateRelationsIterator(); for (int i = 0; i < sentence.ClausesCount; i++) { relationsIterator.Reset(); relationsIterator.AddClauseNoAndVariantNo(i, bestVariantsNombers[i]); relationsIterator.BuildRelations(); relations.Add(i, new List <IRelation>()); for (int j = 0; j < relationsIterator.RelationsCount; j++) { IRelation rel = relationsIterator.get_Relation(j); relations[i].Add(rel); } } return(relations); }
public void DeleteWordsByLength(int length) { var _words = sentences.SelectMany(x => x.Words). Where(x => x.Length == length && x[0].IsVowel == false).Distinct(); for (int i = 0; i < sentences.Count; i++) { ISentence sentence = sentences[i]; for (int j = 0; j < _words.Count(); j++) { while (_words.Count() != 0 && sentence.Contains(_words.ToArray()[j])) { int spaceIndex = sentence.ToList().IndexOf(_words.ToArray()[j]) - 1; sentence.Remove(_words.ToArray()[j]); sentence.RemoveAtIndex(spaceIndex); } } } }
/// <summary> /// Строит массив в котором содержатся номера лучших вариантов /// клауз данного предложения (что считается лучшим - спросить у Сокирко) /// </summary> /// <param name="sentence"></param> /// <returns></returns> private int[] getBestVariantsNombers(ISentence sentence) { int[] bestVariantsNombers = new int[sentence.ClausesCount]; for (int i = 0; i < sentence.ClausesCount; i++) { IClause clo = sentence.get_Clause(i); int bestWeight = 0;//Int32.MaxValue;//0;//!!! for (int j = 0; j < clo.VariantsCount; j++) { ClauseVariant cloVar = clo.get_ClauseVariant(j); if (bestWeight < cloVar.VariantWeight) { bestWeight = cloVar.VariantWeight; bestVariantsNombers[i] = j; } } } return(bestVariantsNombers); }
public static RatingData CalculateRating(this ISentence sentence) { var data = new RatingData(); var important = sentence.Occurrences.GetImportant(); IWordItem firstWord = null; foreach (var wordItem in important) { if (firstWord == null) { firstWord = wordItem; } if (wordItem.Relationship.Sentiment == null) { continue; } data.AddSentiment(wordItem.Relationship.Sentiment.DataValue); } if (firstWord == null) { return(data); } if (!WordTypeResolver.Instance.IsInvertingConjunction(firstWord.Text)) { return(data); } if (!data.HasValue) { // make opposite to previous part and twice lower var previous = sentence.Previous?.CalculateRating().RawRating; if (previous != null) { data.AddSentiment(new SentimentValueData(-previous.Value / 2)); } } return(data); }
public static string TranslateToSpanish(ISentence sentence, string name) { if (sentence.SentenceId == Sentences.HaveYouAlreadyDecidedOnAHome) { return($"Gran {name}. Para empezar, veamos dónde estás actualmente en el proceso. ¿Ya te has decidido por un hogar?"); } if (sentence.SentenceId == Sentences.OkToGetIncomeAndEmploymentInfo) { return($"No es raro {name}, puedo ayudar a determinar eso. Solo necesito obtener información de verificación de ingresos y empleo. ¿OKAY?"); } if (sentence.SentenceId == Sentences.CanYouProvideW2Informaion) { return("¿Sería capaz de proporcionar cualquier información W-2 ahora, por ejemplo, en los últimos años? Puedes subir aquí si es así."); } if (sentence.SentenceId == Sentences.PleaseUploadFiles) { return("Genial, vamos a subirlo ahora, solo pregúntame si tienes alguna pregunta al respecto "); } return(null); }
/// <summary> /// Method to replace some words with other words of different length /// Predicate checks if word have correct length /// </summary> /// <param name="sentence"></param> /// <param name="predicate"></param> /// <param name="sentenceElements"></param> /// <returns></returns> public static ICollection <ISentenceElement> ReplaceWord(ISentence sentence, Predicate <IWord> predicate, ICollection <ISentenceElement> sentenceElements) { var newSentenceElements = sentence.SentenceElements.ToList(); var matchingWords = GetMatchingElements(newSentenceElements, predicate); if (matchingWords.Any()) { foreach (var element in matchingWords) { var index = newSentenceElements.IndexOf((ISentenceElement)element); newSentenceElements.Remove((ISentenceElement)element); // Remove certain element from sentence newSentenceElements.RemoveAt(index); // Remove separator that was left after removing word newSentenceElements.InsertRange(index, sentenceElements); // Add new sentence element in position of removed element } } return(newSentenceElements.Count != 0 ? new List <ISentenceElement>(newSentenceElements) : null); // return new list of sentence elements if it is not empty }
public TextParser() { _text = new TextModel.Text(); _currentSentence = new Sentence(); _actions = new Dictionary <char, Action> { { '.', endOfSentenceAction }, { '!', endOfSentenceAction }, { '?', endOfSentenceAction }, { ' ', spaceAction }, { ',', endOfWordAction }, { ':', endOfWordAction }, { '-', dashAction }, { '\"', quoteAction } }; }
IToken ITextFactory.CreateToken(ISentence sentence, Span span, string lexeme) { if (sentence == null) { throw new ArgumentNullException(nameof(sentence)); } if (span == null) { throw new ArgumentNullException(nameof(span)); } var s = sentence as Sentence; if (s != null) { return(CreateToken(s, span, lexeme)); } throw new NotSupportedException("The sentence type " + sentence.GetType().Name + " is not supported."); }
public object VisitQuantifiedSentence(QuantifiedSentence sentence, object arg) { ISet <Variable> seenSoFar = (ISet <Variable>)arg; // Keep track of what I have to subst locally and // what my renamed variables will be. IDictionary <Variable, ITerm> localSubst = new Dictionary <Variable, ITerm>(); IList <Variable> replVariables = new List <Variable>(); foreach (Variable v in sentence.Variables) { // If local variable has be renamed already // then I need to come up with own name if (seenSoFar.Contains(v)) { var sV = new Variable(quantifiedIndexical.GetPrefix() + quantifiedIndexical.GetNextIndex()); localSubst[v] = sV; // Replacement variables should contain new name for variable replVariables.Add(sV); } else { // Not already replaced, this name is good replVariables.Add(v); } } // Apply the local subst ISentence subst = substVisitor.Subst(localSubst, sentence.Quantified); // Ensure all my existing and replaced variable // names are tracked seenSoFar.UnionWith(replVariables); var sQuantified = (ISentence)subst.Accept(this, arg); return(new QuantifiedSentence(sentence.Quantifier, replVariables, sQuantified)); }
public override void VisitSentences(ISentences sentencesParam, IHighlightingConsumer consumer) { string lastText = null; ISentence lastSentence = null; ISentence startSentence = null; const string message = "Statements can be simplified"; foreach (var sentence in sentencesParam.SentenceListEnumerable) { string text; if (sentence.Statement != null && sentence.Statement.Subject != null && !string.IsNullOrEmpty(text = sentence.Statement.Subject.GetText())) { if (text.Equals(lastText, StringComparison.Ordinal)) { if (startSentence == null) { startSentence = lastSentence; } } else { if (startSentence != null) { this.AddSentenceSuggestionHighlighting(consumer, message, startSentence, lastSentence); startSentence = null; } } lastSentence = sentence; lastText = text; } } if (startSentence != null) { this.AddSentenceSuggestionHighlighting(consumer, message, startSentence, lastSentence); } }
public static ISentence DropOuterQuantifiers(ISentence sentence) { switch (sentence.GetSentenceType()) { case SentenceType.Predicate: return(sentence); case SentenceType.SentenceConnectiveSentence: return(sentence); default: //QuantifierVariableSentence var quantifiedSentence = sentence as QuantifierVariableSentence; if (quantifiedSentence.Quantifier == Quantifier.All) { return(DropOuterQuantifiers(quantifiedSentence.Sentence)); } else { return(sentence); } } }
public bool TryParse(string text, out ISentence stmt) { // text must be of the form "how much is pish glob ?". // Should start with how much is // Must end in ? // Everthing in between is the number stmt = null; if (text.StartsWith("how much is ", StringComparison.Ordinal) == false) { return(false); } if (text.EndsWith("?", StringComparison.Ordinal) == false) { return(false); } var number = text .Replace("how much is ", string.Empty) .Replace(" ?", string.Empty); stmt = new NumberConversionQuestion(number); return(true); }
private void buttonGetAnswer_Click(object sender, EventArgs e) { if (listBoxAnswerType.SelectedItem == null) { //распознать // sentence = knowledgeBase.ParseSentence(knowledgeBase, textBoxAnwerAsString.Text); } else { var s = ReadSentenceFromPanel(); if (sentence == null) { sentence = s; } else { sentence = new SentenceConnectiveSentence(sentence, s, "^"); } } var answer = knowledgeBase.BackwardChain(sentence); var m = MessageBox.Show(sentence.ToString(), answer.Successful ? "True" : "False", MessageBoxButtons.OK); }
/// <summary> /// Creates the <see cref="ICategory"/> object. /// </summary> /// <param name="sentence">The sentence.</param> /// <param name="dict">The scored dictionary of categories.</param> /// <returns>The new <see cref="ICategory"/> object or a <c>null</c> value if the category is invalid or should be ignored.</returns> public ICategory CreateCategory(ISentence sentence, Dictionary <string, double> dict) { var key = string.Empty; var prob = double.MinValue; foreach (var pair in dict) { if (prob >= pair.Value) { continue; } prob = pair.Value; key = pair.Key; } // returns the category with the highest probability. return(new Category { Name = key, Probability = dict[key] }); }
public ICollection <ISentenceElement> ReplaceWord(ISentence sentence, Predicate <IWord> predicate, ICollection <ISentenceElement> sentenceElements) { var newSentenceElements = sentence.SentenceElements.ToList(); var matchingWords = GetMatchingElements(newSentenceElements, predicate); if (matchingWords.Any()) { foreach (var element in matchingWords) { var index = newSentenceElements.IndexOf(element); newSentenceElements.Remove(element); newSentenceElements.RemoveAt(index); newSentenceElements.InsertRange(index, sentenceElements); } } return(newSentenceElements.Count != 0 ? new List <ISentenceElement>(newSentenceElements) : null); }
public IInferenceResult Ask(FOLKnowledgeBase kb, ISentence query) { // Assertions on the type queries this Inference procedure // supports if (!(query is IAtomicSentence)) { throw new ArgumentOutOfRangeException("query", "Only Atomic Queries are supported."); } IList <Literal> goals = new List <Literal>(); goals.Add(new Literal((IAtomicSentence)query)); var ansHandler = new BCAskAnswerHandler(); IList <IList <ProofStepBwChGoal> > allProofSteps = this.Folbcask(kb, ansHandler, goals, new Dictionary <Variable, ITerm>()); ansHandler.SetAllProofSteps(allProofSteps); return(ansHandler); }
public AnswerHandler(FOLKnowledgeBase kb, ISentence aQuery, long maxQueryTime) { var ts = DateTime.Now - DateTime.MinValue; this.finishTime = (long)ts.TotalMilliseconds + maxQueryTime; ISentence refutationQuery = new NotSentence(aQuery); // Want to use an answer literal to pull // query variables where necessary Literal answerLiteral = kb.CreateAnswerLiteral(refutationQuery); answerLiteralVariables = kb.CollectAllVariables(answerLiteral .AtomicSentence); // Create the Set of Support based on the Query. if (answerLiteralVariables.Count > 0) { ISentence refutationQueryWithAnswer = new ConnectedSentence( Connectors.Or, refutationQuery, (ISentence)answerLiteral.AtomicSentence.Copy()); sos = CreateChainsFromClauses(kb .ConvertToClauses(refutationQueryWithAnswer)); answerChain.AddLiteral(answerLiteral); } else { sos = CreateChainsFromClauses(kb .ConvertToClauses(refutationQuery)); } foreach (Chain s in sos) { s.SetProofStep(new ProofStepGoal(s)); } }
public ICollection <ISentence> ReplaceWord(string str, int number, Parsing parser, int length) { ICollection <ISentence> newCollection = DuplicateCollection(); ISentence sentence = newCollection.ElementAt(number); foreach (var component in sentence.ComponentsCollection) { if (component.GetType() == typeof(Word)) { if ((component as Word).Component.Length == length) { (component as Word).Component = str; } } } string buffer = null; foreach (var component in sentence.ComponentsCollection) { buffer += component.Component; } sentence.ComponentsCollection = parser.GetSentenceComponent(buffer); return(newCollection); }
private int isBrecket(int wordNomber, ISentence sent, LongOperationAttribut attr) { string word = sent.get_Word(wordNomber).WordStr; for (int i = 0; i < attr.attributSequence.Count; i++) { if (attr.attributSequence[i] is Brackets) { Brackets br = attr.attributSequence[i] as Brackets; if ((br.atribut1.word == word) || (br.atribut2.word == word)) { return(i); } for (int j = 0; j < br.unionsForAttr2.Count; j++) { if ((br.unionsForAttr2[j] as ElementaryAttribut).word == word) { return(i); } } } } return(-1); }
/// <summary> /// Creates the <see cref="ICategory"/> object. /// </summary> /// <param name="sentence">The sentence.</param> /// <param name="dict">The scored dictionary of categories.</param> /// <returns>The new <see cref="ICategory"/> object or a <c>null</c> value if the category is invalid or should be ignored.</returns> public ICategory CreateCategory(ISentence sentence, Dictionary<string, double> dict) { var key = string.Empty; var prob = double.MinValue; foreach (var pair in dict) { if (prob >= pair.Value) continue; prob = pair.Value; key = pair.Key; } // returns the category with the highest probability. return new Category { Name = key, Probability = dict[key] }; }
public void AddSentence(ISentence sentence) { _sentences.Add(sentence); }
IEntity ITextFactory.CreateEntity(ISentence sentence, Span span) { var s = sentence as Sentence; if (s != null) return CreateEntity(s, span); throw new NotSupportedException("The sentence type " + sentence.GetType().Name + " is not supported."); }
IToken ITextFactory.CreateToken(ISentence sentence, Span span, string lexeme) { if (sentence == null) throw new ArgumentNullException("sentence"); if (span == null) throw new ArgumentNullException("span"); var s = sentence as Sentence; if (s != null) return CreateToken(s, span, lexeme); throw new NotSupportedException("The sentence type " + sentence.GetType().Name + " is not supported."); }
public static ISentence AddToTarget(ISentence declarationToAdd, ICreationTarget target) { var inserter = new NTriplesPrefixInserter(declarationToAdd, target); return inserter.InsertRule(); }
private void AddSentenceSuggestionHighlighting( IHighlightingConsumer consumer, string message, ISentence startElement, ISentence endElement) { var highlighting = new HintRangeHighlighting<ISentence>(startElement, endElement, message); IFile file = startElement.GetContainingFile(); if (file != null) { consumer.AddHighlighting(highlighting, file); } }
public NTriplesPrefixInserter(ISentence declarationToAdd, ICreationTarget target) { this.myDeclarationToAdd = declarationToAdd; this.myTarget = target; }