AnalyzeMorphology() public method

public AnalyzeMorphology ( string phrase, int id_language ) : AnalysisResults
phrase string
id_language int
return AnalysisResults
    public bool ProcessSample_WordEntryOnly(SampleData sample)
    {
        if (sample.morphology == null)
        {
            sample.morphology = gren.AnalyzeMorphology(sample.sample, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_TOKENIZE_ONLY);
        }

        for (int iword = 1; iword < sample.morphology.Count - 1; ++iword)
        {
            SolarixGrammarEngineNET.SyntaxTreeNode token = sample.morphology[iword];
            string word = token.GetWord().ToLower();

            int id_entry = token.GetEntryID();

            int f;
            if (wordentry_stat.TryGetValue(id_entry, out f))
            {
                wordentry_stat[id_entry] = f + 1;
            }
            else
            {
                wordentry_stat.Add(id_entry, 1);
            }
        }

        return(true);
    }
Esempio n. 2
0
    public bool ProcessSample(string line)
    {
        n_learn_samples++;

        // Морфологический разбор
        using (SolarixGrammarEngineNET.AnalysisResults tokens = gren.AnalyzeMorphology(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY))
        {
            List <string> sfx       = new List <string>();
            List <int>    sfx_index = new List <int>();

            List <string> sfx_lemma       = new List <string>();
            List <int>    sfx_lemma_index = new List <int>();

            int last_word_index = tokens.Count - 1;

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

                string suffix = GetTokenSuffix(iword, last_word_index, tokens[iword]);
                sfx.Add(suffix);

                int index = MatchSuffix(suffix, true);
                sfx_index.Add(index);

                int    ekey  = tokens[iword].GetEntryID();
                string ename = gren.GetEntryName(ekey);
                string lemma;
                if (IsUnknownLexem(ename))
                {
                    lemma = word;
                }
                else
                {
                    lemma = ename.ToLower();
                }

                sfx_lemma.Add(GetSuffix(lemma));
                sfx_lemma_index.Add(MatchSuffix(GetSuffix(lemma), true));
            }

            for (int iword = 1; iword < tokens.Count - 1; ++iword)
            {
                string tag1 = TagLabel(-1, sfx_index[iword - 1]);
                string tag2 = TagLabel(0, sfx_index[iword]);
                string tag3 = TagLabel(1, sfx_index[iword + 1]);

                string res = ResultLabel(sfx_lemma_index[iword]);
                WriteTrain(tag1, tag2, tag3, res);
            }
        }

        return(true);
    }
Esempio n. 3
0
    public bool ProcessSample(string line)
    {
        // Морфологический разбор
        using (SolarixGrammarEngineNET.AnalysisResults tokens = gren.AnalyzeMorphology(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY))
        {
            int last_word_index = tokens.Count - 1;
            for (int i = 0; i < tokens.Count; ++i)
            {
                SolarixGrammarEngineNET.SyntaxTreeNode token = tokens[i];
                int suffix_id1 = GetTokenSuffix(i, last_word_index, token);

                int nver = token.VersionCount();
                for (int j = 0; j < nver; ++j)
                {
                    int    ver_ekey   = token.GetVersionEntryID(j);
                    string ename      = gren.GetEntryName(ver_ekey);
                    int    suffix_id2 = GetFormSuffix(i, last_word_index, ename);
                }
            }
        }

        using (SolarixGrammarEngineNET.AnalysisResults projs = gren.AnalyzeMorphology(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_TOKENIZE_ONLY))
        {
            int last_word_index = projs.Count - 1;
            for (int i = 0; i < projs.Count; ++i)
            {
                SolarixGrammarEngineNET.SyntaxTreeNode token = projs[i];
                int suffix_id1 = GetTokenSuffix(i, last_word_index, token);

                int nver = token.VersionCount();
                for (int j = 0; j < nver; ++j)
                {
                    int    ver_ekey   = token.GetVersionEntryID(j);
                    string ename      = gren.GetEntryName(ver_ekey);
                    int    suffix_id2 = GetFormSuffix(i, last_word_index, ename);
                }
            }
        }


        return(true);
    }
    public void ProcessSample(string line)
    {
        if (samples.Contains(line))
        {
            return;
        }

        samples.Add(line);

        bool complete = false;

        using (SolarixGrammarEngineNET.AnalysisResults tokens = gren.AnalyzeSyntax(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY, 0))
        {
            if (tokens.Count == 3)
            {
                complete = true;
                TraverseNode(tokens[1]);
            }
        }

        if (!complete)
        {
            // Морфологический разбор
            using (SolarixGrammarEngineNET.AnalysisResults tokens = gren.AnalyzeMorphology(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY))
            {
                for (int iword = 1; iword < tokens.Count - 2; ++iword)
                {
                    SolarixGrammarEngineNET.SyntaxTreeNode token  = tokens[iword];
                    SolarixGrammarEngineNET.SyntaxTreeNode token2 = tokens[iword + 1];

                    if (IsPreposition(token) && IsNoun(token2))
                    {
                        Store_Prepos_Noun(token, token2);
                    }
                    else if (IsVerb(token) && IsPreposition(token2))
                    {
                        Store_Verb_Prepos(token, token2);
                    }
                }
            }
        }

        return;
    }
    public bool Sentence2Features(string line)
    {
        // синтаксический разбор в дерево
        using (SolarixGrammarEngineNET.AnalysisResults trees = gren.AnalyzeSyntax(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY, 0))
        {
            // Морфологический разбор
            using (SolarixGrammarEngineNET.AnalysisResults tokens = gren.AnalyzeMorphology(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY))
            {
                TreeLookup syntax = new TreeLookup();
                syntax.Collect(tokens, trees, gren);

                if (!syntax.ok)
                {
                    return(false);
                }

                int N = tokens.Count;

                List <WordTags> tag_index = new List <WordTags>();
                List <string>   words     = new List <string>();
                List <string>   labels    = new List <string>();

                WordTags start_t = new WordTags();
                start_t.common = START_id;
                tag_index.Add(start_t);
                words.Add("<START>");
                labels.Add("O");

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

                    SolarixGrammarEngineNET.SyntaxTreeNode token_prev = tokens[iword - 1];

                    WordTags t = new WordTags();

                    t.common   = tags.MatchTags(tokens[iword], gren);
                    t.modality = tags_modality.MatchTags(tokens[iword], gren);
                    t.valency  = tags_valency.MatchTags(tokens[iword], gren);

                    tag_index.Add(t);

                    string crf_word = word.Replace(" ", "_");
                    words.Add(crf_word);

                    labels.Add(syntax.GetTokenLabel(iword));
                }

                WordTags end_t = new WordTags();
                end_t.common = END_id;
                tag_index.Add(end_t);
                words.Add("<END>");
                labels.Add("O");

                System.Text.StringBuilder b = new System.Text.StringBuilder();

                int last_word_index = tokens.Count - 1;
                for (int iword = 0; iword < tokens.Count; ++iword)
                {
                    b.Length = 0;

                    string output_label = labels[iword];
                    string word         = words[iword];

//     PullFeatures1( b, tag_index, iword, -3 );
                    PullFeatures1(b, tag_index, iword, -2);
                    PullFeatures1(b, tag_index, iword, -1);
                    PullFeatures1(b, tag_index, iword, 0);
                    PullFeatures1(b, tag_index, iword, 1);
                    PullFeatures1(b, tag_index, iword, 2);
//     PullFeatures1( b, tag_index, iword, 3 );

//     PullFeatures2( b, tag_index, iword, -3, -2 );
                    PullFeatures2(b, tag_index, iword, -2, -1);
                    PullFeatures2(b, tag_index, iword, -1, 0);
                    PullFeatures2(b, tag_index, iword, 0, 1);
                    PullFeatures2(b, tag_index, iword, 1, 2);
//     PullFeatures2( b, tag_index, iword, 3, 4 );

//     PullFeatures3( b, tag_index, iword, -3, -2, -1 );
                    PullFeatures3(b, tag_index, iword, -2, -1, 0);
                    PullFeatures3(b, tag_index, iword, -1, 0, 1);
                    PullFeatures3(b, tag_index, iword, 0, 1, 2);
//     PullFeatures3( b, tag_index, iword, 1, 2, 3 );

                    crf_file.WriteLine("{0}{1}", output_label, b.ToString());

                    visual_file.WriteLine("{0}\t{1}\t{2}", word, output_label, tag_index[iword]);
                }

                crf_file.WriteLine("");
                visual_file.WriteLine("");
            }
        }

        return(true);
    }
Esempio n. 6
0
    public bool ProcessSample(string line)
    {
        // Морфологический разбор
        using (SolarixGrammarEngineNET.AnalysisResults tokens = gren.AnalyzeMorphology(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY))
        {
            List <int> token2tags = new List <int>();

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

            int last_word_index = tokens.Count - 1;

            bool all_hit = true;
            for (int i = 0; i < tokens.Count; ++i)
            {
                SolarixGrammarEngineNET.SyntaxTreeNode token = tokens[i];
                string word = token.GetWord().ToLower();

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

                int tt = tags.MatchTags(token, gren);
                if (tt == -1)
                {
                    all_hit = false;
                    break;
                }

                token2tags.Add(tags.GetIndexById(tt));
            }

            if (all_hit)
            {
                for (int i = 0; i < tokens.Count; ++i)
                {
                    int tt1 = token2tags[i];
                    T_counts[tt1]++;

                    //SolarixGrammarEngineNET.SyntaxTreeNode token = tokens[i];
                    //string word = token.GetWord().ToLower();

                    int suffix_id = suffices[i];

                    Dictionary <int, int> word_freq;
                    if (B_counts.TryGetValue(tt1, out word_freq))
                    {
                        int freq0;
                        if (word_freq.TryGetValue(suffix_id, out freq0))
                        {
                            word_freq[suffix_id] = freq0 + 1;
                        }
                        else
                        {
                            word_freq.Add(suffix_id, 1);
                        }
                    }
                    else
                    {
                        word_freq = new Dictionary <int, int>();
                        word_freq.Add(suffix_id, 1);
                        B_counts.Add(tt1, word_freq);
                    }

                    if (i > 0)
                    {
                        int tt0 = token2tags[i - 1];
                        A_counts[tt0, tt1]++;
                    }
                }
            }
        }

        return(true);
    }
    public bool ProcessSample(string line)
    {
        n_learn_samples++;

        // чтобы получить все возможные теги, надо для каждого слова получить все возможные распознавания.
        using (SolarixGrammarEngineNET.AnalysisResults projs = gren.AnalyzeMorphology(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_TOKENIZE_ONLY))
        {
            int last_word_index = projs.Count - 1;

            for (int iword = 0; iword < projs.Count; ++iword)
            {
                for (int iproj = 0; iproj < projs[iword].VersionCount(); ++iproj)
                {
                    string lemma = string.Empty;
                    int    ekey  = projs[iword].GetVersionEntryID(iproj);
                    string ename = gren.GetEntryName(ekey);
                    if (IsUnknownLexem(ename))
                    {
                        lemma = projs[iword].GetWord().ToLower();
                    }
                    else
                    {
                        lemma = ename.ToLower();
                    }

                    string sfx = GetTokenSuffix(iword, last_word_index, lemma);

                    int id_lemma = MatchSuffix(sfx, true);
                }
            }
        }


        // Морфологический разбор
        using (SolarixGrammarEngineNET.AnalysisResults tokens = gren.AnalyzeMorphology(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY))
        {
            List <string> sfx       = new List <string>();
            List <int>    sfx_index = new List <int>();

            List <string> sfx_lemma       = new List <string>();
            List <int>    sfx_lemma_index = new List <int>();

            int last_word_index = tokens.Count - 1;

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

                string suffix = GetTokenSuffix(iword, last_word_index, tokens[iword]);
                sfx.Add(suffix);

                int index = MatchSuffix(suffix, true);
                sfx_index.Add(index);

                int    ekey  = tokens[iword].GetEntryID();
                string ename = gren.GetEntryName(ekey);
                string lemma;
                if (IsUnknownLexem(ename))
                {
                    lemma = word;
                }
                else
                {
                    lemma = ename.ToLower();
                }

                string lemma_suffix = GetTokenSuffix(iword, last_word_index, lemma);
                sfx_lemma.Add(lemma_suffix);
                sfx_lemma_index.Add(MatchSuffix(lemma_suffix, true));
            }

            for (int iword = 1; iword < tokens.Count - 1; ++iword)
            {
                string tag1 = LemmaLabel(-1, sfx_lemma_index[iword - 1]); // для Витерби

                // features как контекст +/-1 слово вокруг текущего
                string tag2 = TagLabel(-1, sfx_index[iword - 1]);
                string tag3 = TagLabel(0, sfx_index[iword]);
                string tag4 = TagLabel(1, sfx_index[iword + 1]);

                string res = ResultLabel(sfx_lemma_index[iword]);

                WriteTrain(tag1, tag2, tag3, tag4, res);
            }
        }

        return(true);
    }
    public bool ProcessSample(string line)
    {
        int occurence_count = 0;

        // Морфологический разбор
        using (SolarixGrammarEngineNET.AnalysisResults tokens = gren.AnalyzeMorphology(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY))
        {
            for (int i = 1; i < tokens.Count - 1; ++i)
            {
                SolarixGrammarEngineNET.SyntaxTreeNode token = tokens[i];
                string word = token.GetWord().ToLower();

                if (retrieve_omonyms_from_samples)
                {
                    if (omonyms.Contains(word))
                    {
                        occurence_count++;
                        omonym_processors[word].ProcessSample(line, tokens, LanguageID, gren);
                    }
                    else if (!not_omonyms.Contains(word) && omonyms.Count < MaxOmonymPerSession)
                    {
                        bool is_omonym = false;

                        if (!ignore_omonyms.Contains(word))
                        {
                            // сделаем проекцию слова
                            int id_class0 = -1;
                            using (SolarixGrammarEngineNET.WordProjections projs = gren.FindWordForm(word))
                            {
                                for (int j = 0; j < projs.Count; ++j)
                                {
                                    int id_entry = projs.GetEntryKey(j);
                                    int id_class = gren.GetEntryClass(id_entry);
                                    if (id_class0 == -1)
                                    {
                                        id_class0 = id_class;
                                    }
                                    else if (id_class0 != id_class)
                                    {
                                        is_omonym = true;
                                        break;
                                    }
                                }
                            }

                            if (is_omonym)
                            {
                                omonyms.Add(word);
                                OmonymProcessor processor = new OmonymProcessor(word);
                                omonym_processors.Add(word, processor);

                                occurence_count++;
                                omonym_processors[word].ProcessSample(line, tokens, LanguageID, gren);
                            }
                            else
                            {
                                not_omonyms.Add(word);
                            }
                        }
                    }
                }
                else if (omonyms.Contains(word))
                {
                    occurence_count++;
                    omonym_processors[word].ProcessSample(line, tokens, LanguageID, gren);
                }
            }
        }

        return(occurence_count > 0);
    }
Esempio n. 9
0
    static void Main(string[] args)
    {
        string dictionary_path     = @"e:\MVoice\lem\bin-windows\dictionary.xml"; // путь к словарной базе
        string samples_path        = @"E:\MVoice\lem\Слова\rus\SENT5.plain.txt";  // путь к файлу со списком предложений (одно предложение на одной строке)
        int    NSAMPLE             = 20000;                                       // сколько предложений максимум обработать
        int    START_INDEX         = 0;                                           // порядковый номер первого обрабатываемого предложений в исходном файле
        int    MAXARGS             = 20;                                          // beam size
        bool   append_result       = false;                                       // если леммы надо добавлять к существующему файлу, а не формировать файл с нуля
        string save_path           = null;                                        // путь к файлу, куда будут записаны леммы
        int    source_format       = 0;                                           // 0 - token per line, 1 - sentence per line
        bool   output_lemmas       = true;                                        // в результат записывать леммы с приведением к нижнему регистру
        bool   output_suffix       = false;
        bool   output_words        = false;                                       // в результат записывать исходные слова с приведением к нижнему регистру
        int    suffix_len          = 0;
        int    min_sentence_length = 0;                                           // фильтр по минимальной длине предложений
        int    max_sentence_length = int.MaxValue;                                // фильтр по максимальной длине предложений
        bool   reject_unknown      = false;                                       // отбрасывать предложения с несловарными токенами
        bool   emit_eol            = false;                                       // добавлять в выходной файл токены <EOL> для маркировки конца предложения
        int    eol_count           = 0;                                           // кол-во вставляемых <EOL>, гарантированно перекрывающее размер окна в word2vec

        List <System.Text.RegularExpressions.Regex> rx_stop = new List <System.Text.RegularExpressions.Regex>();

        for (int i = 0; i < args.Length; ++i)
        {
            if (args[i] == "-dict")
            {
                ++i;
                dictionary_path = args[i];
            }
            else if (args[i] == "-samples")
            {
                ++i;
                samples_path = args[i];
            }
            else if (args[i] == "-source_format")
            {
                ++i;
                source_format = int.Parse(args[i]);
            }
            else if (args[i] == "-append")
            {
                // Добавлять в конец существующего файла
                append_result = true;
            }
            else if (args[i] == "-emit_eol")
            {
                ++i;
                eol_count = int.Parse(args[i]);
                if (eol_count > 0)
                {
                    emit_eol = true;
                }
            }
            else if (args[i] == "-result")
            {
                // Способ обработки токенов:
                // lemma  => лемматизация
                // suffix => усечение до псевдосуффикса длиной -suffix_len
                // raw    => исходные слова
                ++i;
                output_lemmas = false;
                output_suffix = false;
                output_words  = false;

                if (args[i] == "suffix")
                {
                    output_suffix = true;
                }
                else if (args[i] == "lemma")
                {
                    output_lemmas = true;
                }
                else if (args[i] == "raw")
                {
                    output_words = true;
                }
                else
                {
                    throw new ApplicationException(string.Format("Unknown result format: {0}", args[i]));
                }
            }
            else if (args[i] == "-save")
            {
                // Путь к файлу, куда будут записываться результаты обработки
                ++i;
                save_path = args[i];
            }
            else if (args[i] == "-nsample")
            {
                // кол-во обрабатываемых предложений, начиная с -start_index
                ++i;
                NSAMPLE = int.Parse(args[i]);
            }
            else if (args[i] == "-min_sent_len")
            {
                // Обрабатывать только предложения, содержащие не менее NNN токенов
                ++i;
                min_sentence_length = int.Parse(args[i]);
            }
            else if (args[i] == "-max_sent_len")
            {
                // Обрабатывать только предложения, содержащие не более NNN токенов
                ++i;
                max_sentence_length = int.Parse(args[i]);
            }
            else if (args[i] == "-suffix_len")
            {
                ++i;
                suffix_len = int.Parse(args[i]);
            }
            else if (args[i] == "-start_index")
            {
                // Начинать обработку с предложения с указанным индексом
                ++i;
                START_INDEX = int.Parse(args[i]);
            }
            else if (args[i] == "-reject_unknown")
            {
                reject_unknown = true;
            }
            else if (args[i] == "-rx_stop")
            {
                ++i;
                using (System.IO.StreamReader rdr = new System.IO.StreamReader(args[i]))
                {
                    while (!rdr.EndOfStream)
                    {
                        string line = rdr.ReadLine();
                        if (line == null)
                        {
                            break;
                        }

                        line = line.Trim();
                        if (line.Length > 0)
                        {
                            rx_stop.Add(new System.Text.RegularExpressions.Regex(line));
                        }
                    }
                }
            }
            else
            {
                throw new ApplicationException(string.Format("Unknown option {0}", args[i]));
            }
        }


        Samples sources = null;

        if (source_format == 1)
        {
            sources = new Samples1(samples_path);
        }
        else
        {
            sources = new Samples2(samples_path);
        }

        sources.SetMinSentenceLen(min_sentence_length);
        sources.SetMaxSentenceLen(max_sentence_length);

        if (output_suffix || output_words)
        {
            sources.SetTokenDelimiter('|');
        }

        SolarixGrammarEngineNET.GrammarEngine2 gren = null;
        gren = new SolarixGrammarEngineNET.GrammarEngine2();

        if (output_lemmas)
        {
            gren.Load(dictionary_path, true);
        }

        int counter     = -1;
        int n_processed = 1;
        int MAX_COUNT   = NSAMPLE;

        int LanguageID  = SolarixGrammarEngineNET.GrammarEngineAPI.RUSSIAN_LANGUAGE;
        int Constraints = 120000 | (MAXARGS << 22); // 2 мин и 20 альтернатив

        SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags Flags = SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_MODEL_ONLY |
                                                                      SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_MODEL;

        // сколько всего предложений
        Console.WriteLine("Counting lines in source file {0}...", samples_path);
        int n_total_lines = sources.TotalCount();

        Console.WriteLine("Total number of lines={0}", n_total_lines.ToString("N0", new System.Globalization.CultureInfo("en-US")));

        System.IO.StreamWriter wrt = new System.IO.StreamWriter(save_path, append_result, new UTF8Encoding(false));

        sources.Start();
        while (true)
        {
            string sample = sources.Next();
            if (sample == null)
            {
                break;
            }

            sample = sample.Trim();

            counter++;

            if (counter < START_INDEX)
            {
                continue;
            }

            if (n_processed >= MAX_COUNT)
            {
                break;
            }

            bool contains_insane_chars = false;
            foreach (char c in sample)
            {
                if (c < 32)
                {
                    contains_insane_chars = true;
                    break;
                }
            }

            if (contains_insane_chars)
            {
                System.Text.StringBuilder b = new StringBuilder(sample.Length);
                foreach (char c in sample)
                {
                    if (c >= 32)
                    {
                        b.Append(c);
                    }
                }

                sample = b.ToString();
            }

            n_processed++;

            if (sample.Length == 0)
            {
                continue;
            }


            if (rx_stop.Count > 0)
            {
                bool reject_this_sample = false;
                foreach (var rx in rx_stop)
                {
                    if (rx.Match(sample).Success)
                    {
                        reject_this_sample = true;
                        break;
                    }
                }

                if (reject_this_sample)
                {
                    continue;
                }
            }

            if (output_lemmas)
            {
                using (SolarixGrammarEngineNET.AnalysisResults tokens = gren.AnalyzeMorphology(sample, LanguageID, Flags, Constraints))
                {
                    for (int i = 1; i < tokens.Count - 1; ++i)
                    {
                        if (char.IsPunctuation(tokens[i].GetWord()[0]))
                        {
                            continue;
                        }

                        int    id_entry = tokens[i].GetEntryID();
                        string lemma    = gren.GetEntryName(id_entry);
                        if (lemma == "???" || lemma.Equals("UNKNOWNENTRY", StringComparison.InvariantCultureIgnoreCase) || lemma.Equals("number_", StringComparison.InvariantCultureIgnoreCase))
                        {
                            lemma = tokens[i].GetWord();
                        }

                        lemma = lemma.ToLower();
                        wrt.Write(" {0}", lemma);
                    }
                }
            }
            else if (output_words)
            {
                string[] tokens = sample.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                foreach (string token in tokens)
                {
                    if (token.Length >= 1 && char.IsPunctuation(token[0]))
                    {
                        continue;
                    }

                    string norma = token.ToLower();
                    wrt.Write(" {0}", norma);
                }
            }
            else if (output_suffix)
            {
                string[] tokens = sample.Split("|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                foreach (string token in tokens)
                {
                    if (token.Length == 0 || (token.Length == 1 && char.IsPunctuation(token[0])))
                    {
                        continue;
                    }

                    string suffix = token;


                    int num;
                    if (int.TryParse(token, out num))
                    {
                        suffix = token.Substring(token.Length - 1);
                    }
                    else if (token.Length > suffix_len + 1)
                    {
                        suffix = "~" + token.Substring(token.Length - suffix_len);
                    }

                    wrt.Write(" {0}", suffix.ToLower());
                }
            }

            if (emit_eol)
            {
                for (int k = 0; k < eol_count; ++k)
                {
                    wrt.Write(" <EOL>");
                }
            }

            Console.WriteLine("[{1}/{2}] {0}", sample, counter, n_total_lines);

            wrt.Flush();
        }

        wrt.Close();

        return;
    }
    public bool ProcessSample(string line)
    {
        // Морфологический разбор
        using (SolarixGrammarEngineNET.AnalysisResults tokens = gren.AnalyzeMorphology(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY))
        {
            List <int> token2tags      = new List <int>();
            List <int> token2selectors = new List <int>();

            int last_word_index = tokens.Count - 1;

            for (int i = 0; i < tokens.Count; ++i)
            {
                SolarixGrammarEngineNET.SyntaxTreeNode token = tokens[i];

                int tt = GetTokenSuffix(i, last_word_index, token);
                token2tags.Add(tt);

                int st = selectors.MatchTags(token, gren);
                token2selectors.Add(st);
            }


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

            // 1 --> 2
            for (int iword = 1; iword < tokens.Count; ++iword)
            {
                // ДИГРАММЫ
                int tags1 = token2tags[iword - 1];
                if (tags1 != -1)
                {
                    int tags2 = token2selectors[iword];
                    if (tags2 != -1)
                    {
                        AddNGram(tags1, tags2);
                    }
                }
            }

            // 2 --> 1
            for (int iword = 1; iword < tokens.Count; ++iword)
            {
                int tags2 = token2tags[iword];
                if (tags2 != -1)
                {
                    int tags1 = token2selectors[iword - 1];

                    if (tags1 != -1)
                    {
                        AddNGram_1(tags1, tags2);
                    }
                }
            }


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

            // 1,2 --> 3
            for (int iword = 2; iword < tokens.Count; ++iword)
            {
                int tags0 = token2tags[iword - 2];
                if (tags0 != -1)
                {
                    int tags1 = token2tags[iword - 1];
                    if (tags1 != -1)
                    {
                        int tags2 = token2selectors[iword];
                        if (tags2 != -1)
                        {
                            AddNGram(tags0, tags1, tags2);
                        }
                    }
                }
            }

            // 1 --> 2 <-- 3
            for (int iword = 2; iword < tokens.Count; ++iword)
            {
                int tags0 = token2tags[iword - 2];
                if (tags0 != -1)
                {
                    int tags1 = token2selectors[iword - 1];
                    if (tags1 != -1)
                    {
                        int tags2 = token2tags[iword];
                        if (tags2 != -1)
                        {
                            AddNGram_1(tags0, tags1, tags2);
                        }
                    }
                }
            }

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

            // 1,2,3 --> 4
            for (int iword = 3; iword < tokens.Count; ++iword)
            {
                int tags0 = token2tags[iword - 3];
                if (tags0 != -1)
                {
                    int tags1 = token2tags[iword - 2];
                    if (tags1 != -1)
                    {
                        int tags2 = token2tags[iword - 1];
                        if (tags2 != -1)
                        {
                            int tags3 = token2selectors[iword];
                            if (tags3 != -1)
                            {
                                AddNGram(tags0, tags1, tags2, tags3);
                            }
                        }
                    }
                }
            }


            // 1,2 --> 3 <-- 4

            for (int iword = 3; iword < tokens.Count; ++iword)
            {
                int tags0 = token2tags[iword - 3];
                if (tags0 != -1)
                {
                    int tags1 = token2tags[iword - 2];
                    if (tags1 != -1)
                    {
                        int tags2 = token2selectors[iword - 1];
                        if (tags2 != -1)
                        {
                            int tags3 = token2tags[iword];
                            if (tags3 != -1)
                            {
                                AddNGram_1(tags0, tags1, tags2, tags3);
                            }
                        }
                    }
                }
            }
        }

        return(true);
    }
    int Constraints = 60000 | (50 << 22); // 1 минута и 50 альтернатив

    private bool Sentence2Features(System.IO.StreamWriter crf_file, SampleData sample)
    {
        // Морфологический разбор

        if (sample.morphology.IsNull())
        {
            sample.morphology = gren.AnalyzeMorphology(sample.sample, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY, Constraints);
        }

        if (sample.tokenization.IsNull())
        {
            sample.tokenization = gren.AnalyzeMorphology(sample.sample, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_TOKENIZE_ONLY, 0);
        }

        //  if( sample.syntax_tree.IsNull() )
        //   sample.syntax_tree = gren.AnalyzeSyntax( sample.sample, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY, 0, Constraints );

        if (sample.morphology.Count != sample.tokenization.Count)
        {
            return(false);
        }

        // ----------------------------------------------
        // Готовим наборы признаков для каждого токена
        // ----------------------------------------------

        List <TokenizerTokenFeatures> token_features = new List <TokenizerTokenFeatures>();

        token_features.AddRange(GetFeatures(0, sample.morphology.Count, sample.morphology[0], sample.tokenization[0]));

        for (int iword = 1; iword < sample.morphology.Count - 1; ++iword)
        {
            List <TokenizerTokenFeatures> f = GetFeatures(iword, sample.morphology.Count, sample.morphology[iword], sample.tokenization[iword]);
            token_features.AddRange(f);
        }

        token_features.AddRange(GetFeatures(sample.morphology.Count - 1, sample.morphology.Count, sample.morphology[sample.morphology.Count - 1], sample.tokenization[sample.morphology.Count - 1]));

        System.Text.StringBuilder b = new System.Text.StringBuilder();

        for (int iword = 0; iword < token_features.Count; ++iword)
        {
            b.Length = 0;

            TokenizerTokenFeatures f_this = token_features[iword];

            PullFeatures1(b, token_features, iword, 0);

            // и соседние слова
            if (CONTEXT_SPAN > 4)
            {
                PullFeatures1(b, token_features, iword, -5);
            }

            if (CONTEXT_SPAN > 3)
            {
                PullFeatures1(b, token_features, iword, -4);
            }

            if (CONTEXT_SPAN > 2)
            {
                PullFeatures1(b, token_features, iword, -3);
            }

            if (CONTEXT_SPAN > 1)
            {
                PullFeatures1(b, token_features, iword, -2);
            }

            PullFeatures1(b, token_features, iword, -1);
            PullFeatures1(b, token_features, iword, 1);

            if (CONTEXT_SPAN > 1)
            {
                PullFeatures1(b, token_features, iword, 2);
            }

            if (CONTEXT_SPAN > 2)
            {
                PullFeatures1(b, token_features, iword, 3);
            }

            if (CONTEXT_SPAN > 3)
            {
                PullFeatures1(b, token_features, iword, 4);
            }

            if (CONTEXT_SPAN > 4)
            {
                PullFeatures1(b, token_features, iword, 5);
            }

            crf_file.Write("{0}", f_this.output_tag);

            crf_file.WriteLine("{0}", b.ToString());
            n_train_patterns++;
        }


        crf_file.WriteLine(""); // пустые строки отделяют предложения
        crf_file.Flush();

        return(true);
    }
    public bool ProcessSample(string line)
    {
        n_learn_samples++;

        if (tokens_file == null)
        {
            tokens_file = new System.IO.StreamWriter(tokens_file_path);
        }

        // чтобы получить все возможные теги, надо для каждого слова получить все возможные распознавания.
        using (SolarixGrammarEngineNET.AnalysisResults projs = gren.AnalyzeMorphology(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_TOKENIZE_ONLY))
        {
            int last_word_index = projs.Count - 1;

            for (int iword = 0; iword < projs.Count; ++iword)
            {
                for (int iproj = 0; iproj < projs[iword].VersionCount(); ++iproj)
                {
                    string lemma = string.Empty;
                    int    ekey  = projs[iword].GetVersionEntryID(iproj);
                    string ename = gren.GetEntryName(ekey);
                    if (IsUnknownLexem(ename))
                    {
                        lemma = projs[iword].GetWord().ToLower();
                    }
                    else
                    {
                        lemma = ename.ToLower();
                    }

                    string sfx1 = GetTokenSuffix(iword, last_word_index, lemma);
                    int    id1  = MatchSuffix(sfx1, true);

                    string sfx2 = GetTokenLemmaSuffix(iword, last_word_index, lemma);
                    int    id2  = MatchSuffix(sfx2, true);
                }
            }
        }


        // Морфологический разбор
        using (SolarixGrammarEngineNET.AnalysisResults tokens = gren.AnalyzeMorphology(line, LanguageID, SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_COMPLETE_ONLY))
        {
            test_samples.Add(line);
            test_sample_token_counts.Add(tokens.Count);

            List <string> sfx       = new List <string>();
            List <int>    sfx_index = new List <int>();

            List <string> sfx_lemma       = new List <string>();
            List <int>    sfx_lemma_index = new List <int>();

            int last_word_index = tokens.Count - 1;

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

                if (iword > 0 && iword < tokens.Count - 1)
                {
                    tokens_file.Write("{0}", word);

                    // все допустимые варианты лемматизации
                    int nlemma = 0;
                    for (int j = 0; j < tokens[iword].VersionCount(); ++j)
                    {
                        int    id_entry = tokens[iword].GetVersionEntryID(j);
                        string ename2   = gren.GetEntryName(id_entry);

                        if (IsUnknownLexem(ename2)) // не будем учитывать ошибки лемматизации для не-словарных лексем.
                        {
                            continue;
                        }

                        tokens_file.Write("\t{0}", ename2);

                        nlemma++;
                    }

                    if (nlemma == 0)
                    {
                        tokens_file.Write("\t{0}", word);
                    }

                    tokens_file.WriteLine("");
                }

                string suffix = GetTokenSuffix(iword, last_word_index, tokens[iword]);
                sfx.Add(suffix);

                int index = MatchSuffix(suffix, true);
                sfx_index.Add(index);

                int    ekey  = tokens[iword].GetEntryID();
                string ename = gren.GetEntryName(ekey);
                string lemma;
                if (IsUnknownLexem(ename))
                {
                    lemma = word;
                }
                else
                {
                    lemma = ename.ToLower();
                }

                string lemma_suffix = GetTokenLemmaSuffix(iword, last_word_index, lemma);
                sfx_lemma.Add(lemma_suffix);
                sfx_lemma_index.Add(MatchSuffix(lemma_suffix, true));
            }
            tokens_file.WriteLine("");

            for (int iword = 1; iword < tokens.Count - 1; ++iword)
            {
                string res = ResultLabel(sfx_lemma_index[iword]);

                //string tag0 = LemmaLabel( -1, sfx_lemma_index[iword - 1] ); // для Витерби в MEMM

                if (iword > 1 && iword < tokens.Count - 2)
                {
                    string tag1 = TagLabel(-2, sfx_index[iword - 2]);
                    string tag2 = TagLabel(-1, sfx_index[iword - 1]);
                    string tag3 = TagLabel(0, sfx_index[iword]);
                    string tag4 = TagLabel(1, sfx_index[iword + 1]);
                    string tag5 = TagLabel(2, sfx_index[iword + 2]);

                    WriteTrain(tag1, tag2, tag3, tag4, tag5, res);
                    WriteTest(tag1, tag2, tag3, tag4, tag5, res);
                }
                else
                {
                    string tag2 = TagLabel(-1, sfx_index[iword - 1]);
                    string tag3 = TagLabel(0, sfx_index[iword]);
                    string tag4 = TagLabel(1, sfx_index[iword + 1]);

                    WriteTrain(tag2, tag3, tag4, res);
                    WriteTest(tag2, tag3, tag4, res);
                }
            }

            WriteTestEOS();
        }

        return(true);
    }
Esempio n. 13
0
    static void Execute( string[] args )
    {
        string dictionary_path = @"e:\MVoice\lem\bin-windows\dictionary.xml"; // путь к словарной базе
          string samples_path = @"E:\MVoice\lem\Слова\rus\SENT5.plain.txt"; // путь к файлу со списком предложений (одно предложение на одной строке)
          int NSAMPLE = 20000; // сколько предложений максимум обработать
          int START_INDEX = 0; // порядковый номер первого обрабатываемого предложений в исходном файле
          int MAXARGS = 20; // beam size
          bool append_result = false; // если леммы надо добавлять к существующему файлу, а не формировать файл с нуля
          string save_path = null; // путь к файлу, куда будут записаны леммы
          int source_format = 0; // 0 - token per line, 1 - sentence per line
          bool output_lemmas = true; // в результат записывать леммы с приведением к нижнему регистру
          bool output_suffix = false;
          bool output_words = false; // в результат записывать исходные слова с приведением к нижнему регистру
          int suffix_len = 0;
          int min_sentence_length = 0; // фильтр по минимальной длине предложений
          int max_sentence_length = int.MaxValue; // фильтр по максимальной длине предложений
          bool reject_unknown = false; // отбрасывать предложения с несловарными токенами
          bool emit_eol = false; // добавлять в выходной файл токены <EOL> для маркировки конца предложения
          int eol_count = 0; // кол-во вставляемых <EOL>, гарантированно перекрывающее размер окна в word2vec

          List<System.Text.RegularExpressions.Regex> rx_stop = new List<System.Text.RegularExpressions.Regex>();

          for( int i = 0; i < args.Length; ++i )
          {
           if( args[i] == "-dict" )
           {
        ++i;
        dictionary_path = args[i];
           }
           else if( args[i] == "-samples" )
           {
        ++i;
        samples_path = args[i];
           }
           else if( args[i] == "-source_format" )
           {
        ++i;
        source_format = int.Parse( args[i] );
           }
           else if( args[i] == "-append" )
           {
        // Добавлять в конец существующего файла
        append_result = true;
           }
           else if( args[i] == "-emit_eol" )
           {
        ++i;
        eol_count = int.Parse( args[i] );
        if( eol_count > 0 )
         emit_eol = true;
           }
           else if( args[i] == "-result" )
           {
        // Способ обработки токенов:
        // lemma  => лемматизация
        // suffix => усечение до псевдосуффикса длиной -suffix_len
        // raw    => исходные слова
        ++i;
        output_lemmas = false;
        output_suffix = false;
        output_words = false;

        if( args[i] == "suffix" )
        {
         output_suffix = true;
        }
        else if( args[i] == "lemma" )
        {
         output_lemmas = true;
        }
        else if( args[i] == "raw" )
        {
         output_words = true;
        }
        else throw new ApplicationException( string.Format( "Unknown result format: {0}", args[i] ) );
           }
           else if( args[i] == "-save" )
           {
        // Путь к файлу, куда будут записываться результаты обработки
        ++i;
        save_path = args[i];
           }
           else if( args[i] == "-nsample" )
           {
        // кол-во обрабатываемых предложений, начиная с -start_index
        ++i;
        NSAMPLE = int.Parse( args[i] );
           }
           else if( args[i] == "-min_sent_len" )
           {
        // Обрабатывать только предложения, содержащие не менее NNN токенов
        ++i;
        min_sentence_length = int.Parse( args[i] );
           }
           else if( args[i] == "-max_sent_len" )
           {
        // Обрабатывать только предложения, содержащие не более NNN токенов
        ++i;
        max_sentence_length = int.Parse( args[i] );
           }
           else if( args[i] == "-suffix_len" )
           {
        ++i;
        suffix_len = int.Parse( args[i] );
           }
           else if( args[i] == "-start_index" )
           {
        // Начинать обработку с предложения с указанным индексом
        ++i;
        START_INDEX = int.Parse( args[i] );
           }
           else if( args[i] == "-reject_unknown" )
           {
        reject_unknown = true;
           }
           else if( args[i] == "-rx_stop" )
           {
        ++i;
        using( System.IO.StreamReader rdr = new System.IO.StreamReader( args[i] ) )
        {
         while( !rdr.EndOfStream )
         {
          string line = rdr.ReadLine();
          if( line == null )
           break;

          line = line.Trim();
          if( line.Length > 0 )
          {
           rx_stop.Add( new System.Text.RegularExpressions.Regex( line ) );
          }
         }
        }
           }
           else
        throw new ApplicationException( string.Format( "Unknown option {0}", args[i] ) );
          }

          Samples sources = null;
          if( source_format == 1 )
           sources = new Samples1( samples_path );
          else
           sources = new Samples2( samples_path );

          sources.SetMinSentenceLen( min_sentence_length );
          sources.SetMaxSentenceLen( max_sentence_length );

          if( output_suffix || output_words )
           sources.SetTokenDelimiter( '|' );

          SolarixGrammarEngineNET.GrammarEngine2 gren = null;
          gren = new SolarixGrammarEngineNET.GrammarEngine2();

          if( output_lemmas )
          {
           gren.Load( dictionary_path, true );
          }

          int counter = -1;
          int n_processed = 1;
          int MAX_COUNT = NSAMPLE;

          int LanguageID = SolarixGrammarEngineNET.GrammarEngineAPI.RUSSIAN_LANGUAGE;
          int Constraints = 120000 | ( MAXARGS << 22 ); // 2 мин и 20 альтернатив

          SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags Flags = SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_MODEL_ONLY |
        SolarixGrammarEngineNET.GrammarEngine.MorphologyFlags.SOL_GREN_MODEL;

          // сколько всего предложений
          Console.WriteLine( "Counting lines in source file {0}...", samples_path );
          int n_total_lines = sources.TotalCount();
          Console.WriteLine( "Total number of lines={0}", n_total_lines.ToString( "N0", new System.Globalization.CultureInfo( "en-US" ) ) );

          System.IO.StreamWriter wrt = new System.IO.StreamWriter( save_path, append_result, new UTF8Encoding( false ) );

          sources.Start();
          while( true )
          {
           string sample = sources.Next();
           if( sample == null )
        break;

           sample = sample.Trim();

           counter++;

           if( counter < START_INDEX )
        continue;

           if( n_processed >= MAX_COUNT )
        break;

           bool contains_insane_chars = false;
           foreach( char c in sample )
        if( c < 32 )
        {
         contains_insane_chars = true;
         break;
        }

           if( contains_insane_chars )
           {
        System.Text.StringBuilder b = new StringBuilder( sample.Length );
        foreach( char c in sample )
         if( c >= 32 )
          b.Append( c );

        sample = b.ToString();
           }

           n_processed++;

           if( sample.Length == 0 )
        continue;

           if( rx_stop.Count > 0 )
           {
        bool reject_this_sample = false;
        foreach( var rx in rx_stop )
         if( rx.Match( sample ).Success )
         {
          reject_this_sample = true;
          break;
         }

        if( reject_this_sample )
         continue;
           }

           if( output_lemmas )
           {
        using( SolarixGrammarEngineNET.AnalysisResults tokens = gren.AnalyzeMorphology( sample, LanguageID, Flags, Constraints ) )
        {
         for( int i = 1; i < tokens.Count - 1; ++i )
         {
          if( char.IsPunctuation( tokens[i].GetWord()[0] ) )
           continue;

          int id_entry = tokens[i].GetEntryID();
          string lemma = gren.GetEntryName( id_entry );
          if( lemma == "???" || lemma.Equals( "UNKNOWNENTRY", StringComparison.InvariantCultureIgnoreCase ) || lemma.Equals( "number_", StringComparison.InvariantCultureIgnoreCase ) )
           lemma = tokens[i].GetWord();

          lemma = lemma.ToLower();
          wrt.Write( " {0}", lemma );
         }
        }
           }
           else if( output_words )
           {
        string[] tokens = sample.Split( "|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries );

        foreach( string token in tokens )
        {
         if( token.Length >= 1 && char.IsPunctuation( token[0] ) )
          continue;

         string norma = token.ToLower();
         wrt.Write( " {0}", norma );
        }
           }
           else if( output_suffix )
           {
        string[] tokens = sample.Split( "|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries );

        foreach( string token in tokens )
        {
         if( token.Length == 0 || ( token.Length == 1 && char.IsPunctuation( token[0] ) ) )
          continue;

         string suffix = token;

         int num;
         if( int.TryParse( token, out num ) )
          suffix = token.Substring( token.Length - 1 );
         else if( token.Length > suffix_len + 1 )
          suffix = "~" + token.Substring( token.Length - suffix_len );

         wrt.Write( " {0}", suffix.ToLower() );
        }
           }

           if( emit_eol )
        for( int k = 0; k < eol_count; ++k )
         wrt.Write( " <EOL>" );

           Console.WriteLine( "[{1}/{2}] {0}", sample, counter, n_total_lines );

           wrt.Flush();
          }

          wrt.Close();

          return;
    }