Пример #1
0
    public bool MatchPartOfSpeech(TagMatcher t)
    {
        if (pos != null && t.pos != null)
        {
            foreach (int p2 in t.pos)
            {
                if (pos.Contains(p2))
                {
                    return(true);
                }
            }

            return(false);
        }
        else if (pos != null && t.entry_pos != null)
        {
            foreach (int p2 in t.entry_pos)
            {
                if (pos.Contains(p2))
                {
                    return(true);
                }
            }

            return(false);
        }

        throw new ApplicationException();
    }
Пример #2
0
        public void OrphanOpeningTag()
        {
            var tagMatcher = new TagMatcher();

            tagMatcher.Match("<B>").Should().Be("Expected </B> found #");
            tagMatcher.Match("<B><B>abcd</B>").Should().Be("Expected </B> found #");
        }
Пример #3
0
        public void OrphanClosingTag()
        {
            var tagMatcher = new TagMatcher();

            tagMatcher.Match("</B>").Should().Be("Expected # found </B>");
            tagMatcher.Match("<B>abcd</B></B>").Should().Be("Expected # found </B>");
        }
Пример #4
0
        public void TestMatchesIgnoreCase()
        {
            var matcher = new TagMatcher(new List <string> {
                "abc", "cde", "efg"
            });

            matcher.Matches("AbC").Should().BeTrue();
            matcher.Matches("eFG").Should().BeTrue();
            matcher.Matches("XY").Should().BeFalse();
        }
Пример #5
0
        public void TestGetAllowedEmptyTags()
        {
            string policyFile = AssembleFile("<allowed-empty-tags>\n" +
                                             "    <literal-list>\n" +
                                             "                <literal value=\"td\"/>\n" +
                                             "                <literal value=\"span\"/>\n" +
                                             "    </literal-list>\n" +
                                             "</allowed-empty-tags>\n");

            var policy = Policy.GetInstance(new MemoryStream(Encoding.UTF8.GetBytes(policyFile)));

            TagMatcher actualTags = policy.GetAllowedEmptyTags();

            actualTags.Matches("td").Should().BeTrue();
            actualTags.Matches("span").Should().BeTrue();
        }
Пример #6
0
        public override void OnEnter()
        {
            TagsData component = GameObject.Value.GetComponent <TagsData>();

            TagMatcher            = new TagMatcher();
            TagMatcher.MatchType  = Match;
            TagMatcher.Tags       = Tags;
            TagMatcher.Categories = Categories;
            if (component != null && TagMatcher.isMatch(component.Data))
            {
                base.Fsm.Event(TrueEvent);
            }
            else
            {
                base.Fsm.Event(FalseEvent);
            }
            Finish();
        }
Пример #7
0
    public void Difference(TagMatcher m, List <int> coord_diff_list)
    {
        foreach (var p in pairs)
        {
            if (!m.pairs.Contains(p))
            {
                coord_diff_list.Add(p.CoordID);
            }
        }

        foreach (var p in m.pairs)
        {
            if (!pairs.Contains(p) && !coord_diff_list.Contains(p.CoordID))
            {
                coord_diff_list.Add(p.CoordID);
            }
        }

        return;
    }
Пример #8
0
    public void Load(string lines, SolarixGrammarEngineNET.GrammarEngine2 gren)
    {
        matchers   = new List <TagMatcher>();
        id2matcher = new Dictionary <int, TagMatcher>();
        id2index   = new Dictionary <int, int>();
        index2id   = new Dictionary <int, int>();

        foreach (string line in lines.Split('\n'))
        {
            string l = line.Trim();
            if (!string.IsNullOrEmpty(l))
            {
                TagMatcher m = new TagMatcher(line, gren);
                matchers.Add(m);
                id2matcher.Add(m.GetId(), m);
                id2index.Add(m.GetId(), matchers.Count - 1);
                index2id.Add(matchers.Count - 1, m.GetId());
            }
        }

        return;
    }
Пример #9
0
    public void Check(
        string line,
        ref int total_word_count,
        ref int error_count_no_filter,
        ref int error_count_with_model
        )
    {
        // Морфологический разбор
        using (SolarixGrammarEngineNET.AnalysisResults tokens = gren.AnalyzeMorphology(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY))
        {
            List <List <int> > word2tags     = new List <List <int> >();
            List <int>         selected_tags = new List <int>();

            // Токенизация без использования синтаксических правил
            using (SolarixGrammarEngineNET.AnalysisResults projs = gren.AnalyzeMorphology(line, LanguageID,
                                                                                          SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_TOKENIZE_ONLY /*| SolarixGrammarEngineNET.GrammarEngine.SOL_GREN_DISABLE_FILTERS*/))
            {
                if (tokens.Count != projs.Count)
                {
                    return;
                }

                // Преобразуем все проекции каждого слова в варианты распознавания тегов

                List <int> tag_set = new List <int>();

                int start_tag = -1, end_tag = -1;

                //List<string> words = new List<string>();
                bool unmatched_tag = false;

                List <int> suffices        = new List <int>();
                int        last_word_index = tokens.Count - 1;

                for (int i = 0; i < tokens.Count; ++i)
                {
                    SolarixGrammarEngineNET.SyntaxTreeNode token = tokens[i];
                    string word = token.GetWord().ToLower();
                    //   words.Add(word);

                    int suffix_id = GetTokenSuffix(i, last_word_index, token);
                    suffices.Add(suffix_id);


                    SolarixGrammarEngineNET.SyntaxTreeNode proj = projs[i];
                    List <int> wt = new List <int>();
                    for (int j = 0; j < proj.VersionCount(); ++j)
                    {
                        int id_tag = tags.GetIndexById(tags.MatchTags(proj, j, gren));
                        if (id_tag != -1)
                        {
                            if (!wt.Contains(id_tag))
                            {
                                wt.Add(id_tag);
                            }

                            if (!tag_set.Contains(id_tag))
                            {
                                tag_set.Add(id_tag);
                            }
                        }

                        if (i == 0)
                        {
                            start_tag = id_tag;
                        }
                        else if (i == tokens.Count - 1)
                        {
                            end_tag = id_tag;
                        }
                    }

                    if (wt.Count == 0)
                    {
                        // ни один тег не подошел, это ошибка кодовой книги.
                        unmatched_tag = true;
                    }

                    word2tags.Add(wt);
                    selected_tags.Add(wt[0]);
                }

                if (unmatched_tag)
                {
                    return;
                }

                // -----------------------------------------
                // Посчитаем ошибки до применения модели
                // -----------------------------------------
                int n_err = 0;

                for (int iword = 1; iword < tokens.Count - 1; ++iword)
                {
                    SolarixGrammarEngineNET.SyntaxTreeNode token = tokens[iword];
                    int ekey1     = token.GetEntryID();
                    int id_class1 = gren.GetEntryClass(ekey1);

                    int tag = selected_tags[iword];
                    if (tag != -1)
                    {
                        TagMatcher m = tags[tags.GetIdByIndex(tag)];
                        if (!m.MatchPartOfSpeech(id_class1))
                        {
                            n_err++;
                        }
                    }
                }

                error_count_no_filter += n_err;
                total_word_count      += (tokens.Count - 2);

                int Nword  = tokens.Count; // кол-во последовательных шагов - число слов, включая левую и правую границы
                int Nstate = tag_set.Count;

                // Viterbi trellis

                // вероятности для состояний
                double[,] V = new double[Nword, Nstate];
                for (int t = 0; t < Nword; ++t)
                {
                    for (int s = 0; s < Nstate; ++s)
                    {
                        V[t, s] = 0.0;
                    }
                }

                // backpointers для отслеживания лучшего пути
                int[,] BACKPOINTER = new int[Nword, Nstate];
                for (int t = 0; t < Nword; ++t)
                {
                    for (int s = 0; s < Nstate; ++s)
                    {
                        BACKPOINTER[t, s] = -1; // возможно, надо как-то инициализировать дефолтный путь на случай, если найти лучший не получится - то есть надо проставить от начального до конечного.
                    }
                }
                V[0, tag_set.IndexOf(start_tag)] = 1.0; // начальное состояние - стартуем из этого состояния.

                for (int t = 1; t < Nword; ++t)
                {
                    // проставляем вероятность получения состояний на шаге t, исходя из значений на предыдущем шаге.

                    for (int s2 = 0; s2 < Nstate; ++s2) // состояния на шаге t
                    {
                        double max_v           = 0.0;
                        int    best_prev_state = 0;

                        int id_tag2 = tag_set[s2];

                        double b = 0.0;

                        Dictionary <int, double> bx;
                        if (PB.TryGetValue(id_tag2, out bx))
                        {
                            bx.TryGetValue(suffices[t], out b);
                        }

                        for (int s1 = 0; s1 < Nstate; ++s1) // состояния на шаге t-1
                        {
                            int id_tag1 = tag_set[s1];

                            double vt = V[t - 1, s1] * PA[id_tag1, id_tag2] * b;

                            if (vt > max_v)
                            {
                                max_v           = vt;
                                best_prev_state = s1;
                            }
                        }

                        V[t, s2]           = max_v;
                        BACKPOINTER[t, s2] = best_prev_state;
                    }
                }

                // обратный ход по состояниям, указанным в BACKPOINTER.

                int best_state = tag_set.IndexOf(end_tag);

                for (int t = Nword - 1; t > 0; --t)
                {
                    int best_prev_state = BACKPOINTER[t, best_state];

                    int selected_tag = tag_set[best_prev_state];

                    // Делаем вариант распознавания, давший этот токен, первым в списке.
                    // ATT: грубые ошибки выбора тега не допускаем, то есть разрешаем только те теги, которые были
                    // получены при распознавании слова.
                    if (word2tags[t - 1].Contains(selected_tag))
                    {
                        selected_tags[t - 1] = selected_tag;
                    }
                    else
                    {
                        // ... грубая ошибка выбора тега.
                    }

                    best_state = best_prev_state;
                }


                // Теперь проверяем количество ошибок в выборе частей речи.
                for (int iword = 1; iword < tokens.Count - 1; ++iword)
                {
                    SolarixGrammarEngineNET.SyntaxTreeNode token = tokens[iword];
                    int ekey1     = token.GetEntryID();
                    int id_class1 = gren.GetEntryClass(ekey1);

                    int tag = selected_tags[iword];
                    if (tag != -1)
                    {
                        TagMatcher m = tags[tags.GetIdByIndex(tag)];
                        if (!m.MatchPartOfSpeech(id_class1))
                        {
                            error_count_with_model++;
                        }
                    }
                }
            }
        }

        return;
    }
Пример #10
0
 public SVM_X_Picker(string line, SolarixGrammarEngineNET.GrammarEngine2 gren, int _x_index)
 {
     x_index = _x_index;
     tag     = new TagMatcher(line, gren);
     return;
 }
    public void Check(
        string line,
        ref int total_word_count,
        ref int error_count_no_filter,
        ref int error_count_with_model
        )
    {
        // Морфологический разбор
        using (SolarixGrammarEngineNET.AnalysisResults tokens = gren.AnalyzeMorphology(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY))
        {
            // Токенизация без использования синтаксических правил
            using (SolarixGrammarEngineNET.AnalysisResults projs = gren.AnalyzeMorphology(line, LanguageID,
                                                                                          SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_TOKENIZE_ONLY /*| SolarixGrammarEngineNET.GrammarEngine.SOL_GREN_DISABLE_FILTERS*/))
            {
                if (tokens.Count != projs.Count)
                {
                    return;
                }


                int last_word_index = projs.Count - 1;

                // -----------------------------------------
                // Посчитаем ошибки до применения модели
                // -----------------------------------------
                int n_err = 0;
                for (int iword = 1; iword < last_word_index; ++iword)
                {
                    SolarixGrammarEngineNET.SyntaxTreeNode proj = projs[iword];
                    int ekey0     = proj.GetEntryID();
                    int id_class0 = gren.GetEntryClass(ekey0);

                    // Совпадает с точным значением?
                    SolarixGrammarEngineNET.SyntaxTreeNode token = tokens[iword];
                    int ekey1     = token.GetEntryID();
                    int id_class1 = gren.GetEntryClass(ekey1);

                    if (id_class0 != id_class1)
                    {
                        n_err++;
                    }
                }

                error_count_no_filter += n_err;
                total_word_count      += (tokens.Count - 2);



                List <int> n_pos     = new List <int>(); // кол-во разных частей речи для каждого токена
                List <int> word2tags = new List <int>();

                // Преобразуем все проекции каждого слова в варианты распознавания тегов
                for (int i = 0; i < tokens.Count; ++i)
                {
                    SolarixGrammarEngineNET.SyntaxTreeNode token = tokens[i];
                    int index = GetTokenSuffix(i, last_word_index, token);

                    word2tags.Add(index);

                    // На сколько разных частей речи проецируется данное слово
                    List <int> pos_list = new List <int>();
                    for (int k = 0; k < projs[i].VersionCount(); ++k)
                    {
                        int ekey0     = projs[i].GetVersionEntryID(k);
                        int id_class0 = gren.GetEntryClass(ekey0);
                        if (!pos_list.Contains(id_class0))
                        {
                            pos_list.Add(id_class0);
                        }
                    }

                    n_pos.Add(pos_list.Count);
                }


                List <Dictionary <int, int> > pos_score = new List <Dictionary <int, int> >();
                List <int> pos_score_order = new List <int>();

                // Инициализируем вектор частей речи значениями, которые соответствуют
                // чамым частотным словоформам.
                for (int iword = 0; iword < tokens.Count - 1; ++iword)
                {
                    SolarixGrammarEngineNET.SyntaxTreeNode proj = projs[iword];

                    Dictionary <int, int> p = new Dictionary <int, int>();

                    for (int iproj = 0; iproj < proj.VersionCount(); ++iproj)
                    {
                        int ekey     = proj.GetVersionEntryID(iproj);
                        int id_class = gren.GetEntryClass(ekey);

                        if (!p.ContainsKey(id_class))
                        {
                            if (iproj == 0)
                            {
                                p.Add(id_class, 1);
                            }
                            else
                            {
                                p.Add(id_class, 0);
                            }
                        }
                    }

                    pos_score.Add(p);
                    pos_score_order.Add(1);
                }


                // ---------------------------------
                // теперь применим модель
                // ---------------------------------
                bool use_4grams = true;
                bool use_3grams = true;
                bool use_2grams = true;

                for (int iword = 1; iword < tokens.Count - 1; ++iword)
                {
                    string word = tokens[iword].GetWord();

                    bool applied = false;

                    // ==============
                    // ТЕТРАГРАММЫ
                    // ==============

                    if (use_4grams && !applied && iword > 2)
                    {
                        if (n_pos[iword] > 1) // Выбираем POS для iword на основе iword-3,iword-2,iword-1
                        {
                            int tag0 = word2tags[iword - 3];
                            int tag1 = word2tags[iword - 2];
                            int tag2 = word2tags[iword - 1];

                            List <NGram4> n4_list;
                            Int3          k = new Int3(tag0, tag1, tag2);

                            if (tag0_2_ngram4.TryGetValue(k, out n4_list))
                            {
                                // Перебираем варианты, которые вытекают из наличия тегов tag0,tag1,tag2 и прибавляем очки соответствующим частям речи.
                                foreach (NGram4 n4_probe in n4_list)
                                {
                                    int        tag3 = n4_probe.tags3;
                                    TagMatcher m    = selectors[tag3];

                                    List <KeyValuePair <int, int> > changes = new List <KeyValuePair <int, int> >();

                                    Dictionary <int, int> pos2score = pos_score[iword];

                                    foreach (KeyValuePair <int, int> p in pos2score)
                                    {
                                        if (m.MatchPartOfSpeech(p.Key))
                                        {
                                            int m_freq = ngrams4[n4_probe];
                                            changes.Add(new KeyValuePair <int, int>(p.Key, m_freq));
                                            applied = true;
                                        }
                                    }

                                    foreach (var kv in changes)
                                    {
                                        pos2score[kv.Key] = pos2score[kv.Key] + kv.Value;
                                    }

                                    pos_score_order[iword] = 4;
                                }
                            }
                        }
                        else if (n_pos[iword - 1] > 1 && pos_score_order[iword - 1] < 4) // Выбираем POS для iword-1 на основе iword-3,iword-2,iword
                        {
                            int tag0 = word2tags[iword - 3];
                            int tag1 = word2tags[iword - 2];
                            int tag3 = word2tags[iword];

                            List <NGram4> n4_list;
                            Int3          k = new Int3(tag0, tag1, tag3);

                            if (tag1_2_ngram4.TryGetValue(k, out n4_list))
                            {
                                // Перебираем варианты, которые вытекают из наличия тегов tag0,tag1,tag2 и прибавляем очки соответствующим частям речи.
                                foreach (NGram4 n4_probe in n4_list)
                                {
                                    int        tag2 = n4_probe.tags2;
                                    TagMatcher m    = selectors[tag2];

                                    List <KeyValuePair <int, int> > changes = new List <KeyValuePair <int, int> >();

                                    Dictionary <int, int> pos2score = pos_score[iword];

                                    foreach (KeyValuePair <int, int> p in pos2score)
                                    {
                                        if (m.MatchPartOfSpeech(p.Key))
                                        {
                                            int m_freq = ngrams4_1[n4_probe];
                                            changes.Add(new KeyValuePair <int, int>(p.Key, m_freq));
                                            applied = true;
                                        }
                                    }

                                    foreach (var kv in changes)
                                    {
                                        pos2score[kv.Key] = pos2score[kv.Key] + kv.Value;
                                    }

                                    pos_score_order[iword - 1] = 4;
                                }
                            }
                        }
                    }



                    // ==============
                    // ТРИГРАММЫ
                    // ==============

                    if (use_3grams && !applied && iword > 1)
                    {
                        if (n_pos[iword] > 1) // Выбираем POS для iword на основе iword-2,iword-1
                        {
                            {
                                int tag0 = word2tags[iword - 2];
                                int tag1 = word2tags[iword - 1];

                                List <NGram3> n3_list;
                                Int2          k = new Int2(tag0, tag1);

                                if (tag0_2_ngram3.TryGetValue(k, out n3_list))
                                {
                                    // Перебираем варианты, которые вытекают из наличия тегов tag0,tag1, и прибавляем очки соответствующим частям речи.
                                    foreach (NGram3 n3_probe in n3_list)
                                    {
                                        int        tag2 = n3_probe.tags2;
                                        TagMatcher m    = selectors[tag2];

                                        List <KeyValuePair <int, int> > changes = new List <KeyValuePair <int, int> >();

                                        Dictionary <int, int> pos2score = pos_score[iword];

                                        foreach (KeyValuePair <int, int> p in pos2score)
                                        {
                                            if (m.MatchPartOfSpeech(p.Key))
                                            {
                                                int m_freq = ngrams3[n3_probe];
                                                changes.Add(new KeyValuePair <int, int>(p.Key, m_freq));
                                                applied = true;
                                            }
                                        }

                                        foreach (var kv in changes)
                                        {
                                            pos2score[kv.Key] = pos2score[kv.Key] + kv.Value;
                                        }
                                    }
                                }
                            }


                            if (iword < last_word_index)
                            {
                                // iword-1 --> iword <-- iword+1

                                int tag0 = word2tags[iword - 1];
                                int tag2 = word2tags[iword + 1];

                                List <NGram3> n3_list;
                                Int2          k = new Int2(tag0, tag2);

                                if (tag1_2_ngram3.TryGetValue(k, out n3_list))
                                {
                                    // Перебираем варианты, которые вытекают из наличия тегов tag0,tag2, и прибавляем очки соответствующим частям речи.
                                    foreach (NGram3 n3_probe in n3_list)
                                    {
                                        int        tag1 = n3_probe.tags1;
                                        TagMatcher m    = selectors[tag1];

                                        List <KeyValuePair <int, int> > changes = new List <KeyValuePair <int, int> >();

                                        Dictionary <int, int> pos2score = pos_score[iword];

                                        foreach (KeyValuePair <int, int> p in pos2score)
                                        {
                                            if (m.MatchPartOfSpeech(p.Key))
                                            {
                                                int m_freq = ngrams3_1[n3_probe];
                                                changes.Add(new KeyValuePair <int, int>(p.Key, m_freq));
                                                applied = true;
                                            }
                                        }

                                        foreach (var kv in changes)
                                        {
                                            pos2score[kv.Key] = pos2score[kv.Key] + kv.Value;
                                        }

                                        pos_score_order[iword] = 3;
                                    }
                                }
                            }
                        }
                        else if (n_pos[iword - 1] > 1 && pos_score_order[iword - 1] < 3) // Выбираем POS для iword-1 на основе iword-2,iword
                        {
                            int tag0 = word2tags[iword - 2];
                            int tag2 = word2tags[iword];

                            List <NGram3> n3_list;
                            Int2          k = new Int2(tag0, tag2);

                            if (tag1_2_ngram3.TryGetValue(k, out n3_list))
                            {
                                // Перебираем варианты, которые вытекают из наличия тегов tag0,tag2, и прибавляем очки соответствующим частям речи.
                                foreach (NGram3 n3_probe in n3_list)
                                {
                                    int        tag1 = n3_probe.tags1;
                                    TagMatcher m    = selectors[tag1];

                                    List <KeyValuePair <int, int> > changes = new List <KeyValuePair <int, int> >();

                                    Dictionary <int, int> pos2score = pos_score[iword];

                                    foreach (KeyValuePair <int, int> p in pos2score)
                                    {
                                        if (m.MatchPartOfSpeech(p.Key))
                                        {
                                            int m_freq = ngrams3_1[n3_probe];
                                            changes.Add(new KeyValuePair <int, int>(p.Key, m_freq));
                                            applied = true;
                                        }
                                    }

                                    foreach (var kv in changes)
                                    {
                                        pos2score[kv.Key] = pos2score[kv.Key] + kv.Value;
                                    }

                                    pos_score_order[iword] = 3;
                                }
                            }
                        }
                    }


                    // ==============
                    // ДИГРАММЫ
                    // ==============

                    if (use_2grams && !applied && iword > 1)
                    {
                        if (n_pos[iword] > 1) // Выбираем POS для iword на основе iword-1
                        {
                            {
                                int tag0 = word2tags[iword - 1];

                                List <NGram2> n2_list;
                                if (tag0_2_ngram2.TryGetValue(tag0, out n2_list))
                                {
                                    // Перебираем варианты, которые вытекают из наличия тега tag0, и прибавляем очки соответствующим частям речи.
                                    foreach (NGram2 n2_probe in n2_list)
                                    {
                                        int        tag1 = n2_probe.tags1;
                                        TagMatcher m    = selectors[tag1];

                                        List <KeyValuePair <int, int> > changes = new List <KeyValuePair <int, int> >();

                                        Dictionary <int, int> pos2score = pos_score[iword];

                                        foreach (KeyValuePair <int, int> p in pos2score)
                                        {
                                            if (m.MatchPartOfSpeech(p.Key))
                                            {
                                                int m_freq = ngrams2[n2_probe];
                                                changes.Add(new KeyValuePair <int, int>(p.Key, m_freq));
                                                applied = true;
                                            }
                                        }

                                        foreach (var kv in changes)
                                        {
                                            pos2score[kv.Key] = pos2score[kv.Key] + kv.Value;
                                        }

                                        pos_score_order[iword] = 2;
                                    }
                                }
                            }

                            if (iword < last_word_index)
                            {
                                // iword <-- iword+1
                                int tag1 = word2tags[iword + 1];

                                List <NGram2> n2_list;
                                if (tag1_2_ngram2.TryGetValue(tag1, out n2_list))
                                {
                                    // Перебираем варианты, которые вытекают из наличия тега tag1, и прибавляем очки соответствующим частям речи.
                                    foreach (NGram2 n2_probe in n2_list)
                                    {
                                        int        tag0 = n2_probe.tags0;
                                        TagMatcher m    = selectors[tag0];

                                        List <KeyValuePair <int, int> > changes = new List <KeyValuePair <int, int> >();

                                        Dictionary <int, int> pos2score = pos_score[iword];

                                        foreach (KeyValuePair <int, int> p in pos2score)
                                        {
                                            if (m.MatchPartOfSpeech(p.Key))
                                            {
                                                int m_freq = ngrams2_1[n2_probe];
                                                changes.Add(new KeyValuePair <int, int>(p.Key, m_freq));
                                                applied = true;
                                            }
                                        }

                                        foreach (var kv in changes)
                                        {
                                            pos2score[kv.Key] = pos2score[kv.Key] + kv.Value;
                                        }

                                        pos_score_order[iword] = 2;
                                    }
                                }
                            }
                        }
                        else if (n_pos[iword - 1] > 1 && pos_score_order[iword - 1] == 1) // Выбираем POS для iword-1 на основе iword
                        {
                            int tag1 = word2tags[iword];

                            List <NGram2> n2_list;
                            if (tag1_2_ngram2.TryGetValue(tag1, out n2_list))
                            {
                                // Перебираем варианты, которые вытекают из наличия тега tag1, и прибавляем очки соответствующим частям речи.
                                foreach (NGram2 n2_probe in n2_list)
                                {
                                    int        tag0 = n2_probe.tags0;
                                    TagMatcher m    = selectors[tag0];

                                    List <KeyValuePair <int, int> > changes = new List <KeyValuePair <int, int> >();

                                    Dictionary <int, int> pos2score = pos_score[iword - 1];

                                    foreach (KeyValuePair <int, int> p in pos2score)
                                    {
                                        if (m.MatchPartOfSpeech(p.Key))
                                        {
                                            int m_freq = ngrams2_1[n2_probe];
                                            changes.Add(new KeyValuePair <int, int>(p.Key, m_freq));
                                            applied = true;
                                        }
                                    }

                                    foreach (var kv in changes)
                                    {
                                        pos2score[kv.Key] = pos2score[kv.Key] + kv.Value;
                                    }

                                    pos_score_order[iword - 1] = 2;
                                }
                            }
                        }
                    }
                }



                // Все вероятности перехода учтены.

                // Совпадает ли selected_id_class с требуемыми значениями?
                for (int iword = 1; iword < projs.Count - 1; ++iword)
                {
                    Dictionary <int, int> word_pos_scores = pos_score[iword];
                    int best_score = 0;
                    int best_pos   = -1;
                    foreach (KeyValuePair <int, int> k in word_pos_scores)
                    {
                        if (k.Value > best_score)
                        {
                            best_score = k.Value;
                            best_pos   = k.Key;
                        }
                    }

                    SolarixGrammarEngineNET.SyntaxTreeNode token = tokens[iword];
                    int ekey1     = token.GetEntryID();
                    int id_class1 = gren.GetEntryClass(ekey1);

                    if (best_pos != id_class1)
                    {
                        error_count_with_model++;
                    }
                }
            }
        }


        return;
    }
Пример #12
0
        public IAssetBundle Read(string filename, int filterindex)
        {
            // An sdltm file is an SQLite database.
            // Quickly check the signature will accelerate auto-detection processes.
            // (I know the following code looks silly.)
            using (var s = File.OpenRead(filename))
            {
                if (s.ReadByte() != 'S' ||
                    s.ReadByte() != 'Q' ||
                    s.ReadByte() != 'L' ||
                    s.ReadByte() != 'i' ||
                    s.ReadByte() != 't' ||
                    s.ReadByte() != 'e' ||
                    s.ReadByte() != ' ' ||
                    s.ReadByte() != 'f' ||
                    s.ReadByte() != 'o' ||
                    s.ReadByte() != 'r' ||
                    s.ReadByte() != 'm' ||
                    s.ReadByte() != 'a' ||
                    s.ReadByte() != 't' ||
                    s.ReadByte() != ' ' ||
                    s.ReadByte() != '3' ||
                    s.ReadByte() != '\0')
                {
                    return(null);
                }
            }

            IDbConnection connection = null;
            IDataReader   reader     = null;

            try
            {
                // Try to open the file.

                try
                {
                    var b = new SQLiteConnectionStringBuilder()
                    {
                        DataSource = filename
                    };
                    connection = new SQLiteConnection(b.ConnectionString);
                    connection.Open();
                }
                catch (Exception)
                {
                    return(null);
                }

                // Some sanity check.

                var version = ExecScalar(connection, @"SELECT value FROM parameters WHERE name = 'VERSION'") as string;
                if (version?.StartsWith("8.") != true)
                {
                    return(null);
                }

                var tm_min   = ExecScalarValue <int>(connection, @"SELECT min(id) FROM translation_memories");
                var tm_max   = ExecScalarValue <int>(connection, @"SELECT max(id) FROM translation_memories");
                var tm_count = tm_max - tm_min + 1;
                if (tm_count <= 0 || tm_count > 1000)
                {
                    return(null);
                }

                // Read asset metadata.
                // An asset corresponds to a memory in an sdltm file.

                var assets = new SdltmAsset[tm_count];

                reader = ExecReader(connection, @"SELECT id, name, source_language, target_language FROM translation_memories");
                while (reader.Read())
                {
                    var tmid = reader.GetInt32(0);
                    assets[tmid - tm_min] = new SdltmAsset()
                    {
                        Package    = filename,
                        Original   = reader.GetString(1),
                        SourceLang = reader.GetString(2),
                        TargetLang = reader.GetString(3),
                    };
                }
                reader.Close();
                reader.Dispose();
                reader = null;

                // Read the contents of assets (memories).

                var pool    = new StringPool();
                var matcher = new TagMatcher();

                reader = ExecReader(connection, @"SELECT translation_memory_id, id, source_segment, target_segment, creation_date, creation_user, change_date, change_user FROM translation_units");
                while (reader.Read())
                {
                    var tmid = reader.GetInt32(0);
                    var pair = new SdltmPair()
                    {
                        Id            = reader.GetInt32(1).ToString(),
                        Source        = GetInlineString(reader.GetString(2)),
                        Target        = GetInlineString(reader.GetString(3)),
                        SourceLang    = assets[tmid - tm_min].SourceLang,
                        TargetLang    = assets[tmid - tm_min].TargetLang,
                        _CreationDate = pool.Intern(reader.GetString(4)),
                        _CreationUser = pool.Intern(reader.GetString(5)),
                        _ChangeDate   = pool.Intern(reader.GetString(6)),
                        _ChangeUser   = pool.Intern(reader.GetString(7)),
                    };
                    matcher.MatchTags(pair.Source, pair.Target, reader.GetString(2), reader.GetString(3));
                    assets[tmid - tm_min]._TransPairs.Add(pair);
                }
                reader.Close();
                reader.Dispose();
                reader = null;

                // Fix the serial numbers.

                int serial = 0;
                foreach (var asset in assets)
                {
                    foreach (var pair in asset._TransPairs)
                    {
                        pair.Serial = ++serial;
                    }
                }

                // That's all.

                return(new SimpleAssetBundle(assets, ReaderManager.FriendlyFilename(filename)));
            }
            finally
            {
                reader?.Close();
                reader?.Dispose();
                connection?.Dispose();
            }
        }
Пример #13
0
        public void TestSampleData(Tuple <string, string> testCase)
        {
            var tagMatcher = new TagMatcher();

            tagMatcher.Match(testCase.Item1).Should().Be(testCase.Item2);
        }
Пример #14
0
        public void StringWithSimpleTagsIsCorrectlyTagged()
        {
            var tagMatcher = new TagMatcher();

            tagMatcher.Match("<B>abcd</B>").Should().Be(TagMatcher.CorrectlyTagged);
        }
Пример #15
0
        public void StringWithNoTagsIsCorrectlyTagged()
        {
            var tagMatcher = new TagMatcher();

            tagMatcher.Match("abcd").Should().Be(TagMatcher.CorrectlyTagged);
        }
Пример #16
0
        public void EmptyStringIsCorrectlyTagged()
        {
            var tagMatcher = new TagMatcher();

            tagMatcher.Match("").Should().Be(TagMatcher.CorrectlyTagged);
        }