Example #1
0
        public int checkWord(string answer)
        {
            //несовпадение со словарем
            if (BaseWords.searchCity(answer) == false)
            {
                return(0);
            }

            if (UsedCities.Count == 0)
            {
                UsedCities.Add(answer);
                return(1);
            }

            string pastWord = UsedCities[UsedCities.Count - 1];

            //несовпадение последней бувы с первой
            if (pastWord[pastWord.Length - 1] == 'ы' || pastWord[pastWord.Length - 1] == 'ь' || pastWord[pastWord.Length - 1] == 'Ы' || pastWord[pastWord.Length - 1] == 'Ь')
            {
                if (string.Compare(answer[0].ToString(), pastWord[pastWord.Length - 2].ToString(), true) != 0)
                {
                    return(-2);
                }
            }
            else
            {
                if (string.Compare(answer[0].ToString(), pastWord[pastWord.Length - 1].ToString(), true) != 0)
                {
                    return(-2);
                }
            }

            // слово уже использовалось
            foreach (var city in UsedCities)
            {
                if (city == answer)
                {
                    return(-1);
                }
            }

            UsedCities.Add(answer); //добавляем город в использованные

            return(1);
        }
        /// <summary>
        ///     Initializes the dictionary by loading and parsing the
        ///     dictionary file and the user file.
        /// </summary>
        public void Initialize()
        {
            // clean up data first
            _baseWords.Clear();
            _replaceCharacters.Clear();
            _prefixRules.Clear();
            _suffixRules.Clear();
            _phoneticRules.Clear();
            _tryCharacters = "";


            // the following is used to split a line by white space
            Regex           _spaceRegx = new Regex(@"[^\s]+", RegexOptions.Compiled);
            MatchCollection partMatches;

            string    currentSection = "";
            AffixRule currentRule    = null;
            string    dictionaryPath = Path.Combine(_dictionaryFolder, _dictionaryFile);

            TraceWriter.TraceInfo("Loading Dictionary:{0}", dictionaryPath);

            // open dictionary file
            FileStream fs = null;

            try
            {
                fs = new FileStream(dictionaryPath, FileMode.Open, FileAccess.Read, FileShare.Read);
                using (var sr = new StreamReader(fs, Encoding.UTF8))
                {
                    fs = null;

                    // read line by line
                    while (sr.Peek() >= 0)
                    {
                        string tempLine = sr.ReadLine().Trim();
                        if (tempLine.Length <= 0)
                        {
                            continue;
                        }
                        // check for section flag
                        if (tempLine.StartsWith("[") && tempLine.EndsWith("]"))
                        {
                            // set current section that is being parsed
                            currentSection = tempLine;
                            continue;
                        }

                        // parse line and place in correct object
                        switch (currentSection)
                        {
                        case "[Copyright]":
                            Copyright += tempLine + "\r\n";
                            break;

                        case "[Try]":     // ISpell try chars
                            TryCharacters += tempLine;
                            break;

                        case "[Replace]":     // ISpell replace chars
                            ReplaceCharacters.Add(tempLine);
                            break;

                        case "[Prefix]":     // MySpell prefix rules
                        case "[Suffix]":     // MySpell suffix rules

                            // split line by white space
                            partMatches = _spaceRegx.Matches(tempLine);

                            // if 3 parts, then new rule
                            if (partMatches.Count == 3)
                            {
                                currentRule = new AffixRule();

                                // part 1 = affix key
                                currentRule.Name = partMatches[0].Value;
                                // part 2 = combine flag
                                if (partMatches[1].Value == "Y")
                                {
                                    currentRule.AllowCombine = true;
                                }
                                // part 3 = entry count, not used

                                if (currentSection == "[Prefix]")
                                {
                                    // add to prefix collection
                                    PrefixRules.Add(currentRule.Name, currentRule);
                                }
                                else
                                {
                                    // add to suffix collection
                                    SuffixRules.Add(currentRule.Name, currentRule);
                                }
                            }
                            //if 4 parts, then entry for current rule
                            else if (partMatches.Count == 4)
                            {
                                // part 1 = affix key
                                if (currentRule.Name == partMatches[0].Value)
                                {
                                    AffixEntry entry = new AffixEntry();

                                    // part 2 = strip char
                                    if (partMatches[1].Value != "0")
                                    {
                                        entry.StripCharacters = partMatches[1].Value;
                                    }
                                    // part 3 = add chars
                                    entry.AddCharacters = partMatches[2].Value;
                                    // part 4 = conditions
                                    AffixUtility.EncodeConditions(partMatches[3].Value, entry);

                                    currentRule.AffixEntries.Add(entry);
                                }
                            }
                            break;

                        case "[Phonetic]":     // ASpell phonetic rules
                            // split line by white space
                            partMatches = _spaceRegx.Matches(tempLine);
                            if (partMatches.Count >= 2)
                            {
                                PhoneticRule rule = new PhoneticRule();
                                PhoneticUtility.EncodeRule(partMatches[0].Value, ref rule);
                                rule.ReplaceString = partMatches[1].Value;
                                _phoneticRules.Add(rule);
                            }
                            break;

                        case "[Words]":     // dictionary word list
                            // splits word into its parts
                            string[] parts    = tempLine.Split('/');
                            Word     tempWord = new Word();
                            // part 1 = base word
                            tempWord.Text = parts[0];
                            // part 2 = affix keys
                            if (parts.Length >= 2)
                            {
                                tempWord.AffixKeys = parts[1];
                            }
                            // part 3 = phonetic code
                            if (parts.Length >= 3)
                            {
                                tempWord.PhoneticCode = parts[2];
                            }

                            BaseWords.Add(tempWord.Text, tempWord);
                            break;
                        } // currentSection switch
                    }     // read line
                      // close files
                }
            }
            finally
            {
                if (fs != null)
                {
                    fs.Dispose();
                }
            }

            TraceWriter.TraceInfo("Dictionary Loaded BaseWords:{0}; PrefixRules:{1}; SuffixRules:{2}; PhoneticRules:{3}",
                                  BaseWords.Count, PrefixRules.Count, SuffixRules.Count, PhoneticRules.Count);

            LoadUserFile();

            _initialized = true;
        }
        /// <summary>
        ///     Searches all contained word lists for word
        /// </summary>
        /// <param name="word" type="string">
        ///     <para>
        ///         The word to search for
        ///     </para>
        /// </param>
        /// <returns>
        ///     Returns true if word is found
        /// </returns>
        public bool Contains(string word)
        {
            // clean up possible base word list
            PossibleBaseWords.Clear();

            // Step 1 Search UserWords
            if (UserWords.ContainsKey(word))
            {
                TraceWriter.TraceVerbose("Word Found in User Dictionary: {0}", word);
                return(true);  // word found
            }

            // Step 2 Search BaseWords
            if (BaseWords.ContainsKey(word))
            {
                TraceWriter.TraceVerbose("Word Found in Base Words: {0}", word);
                return(true); // word found
            }

            // Step 3 Remove suffix, Search BaseWords

            // save suffixed words for use when removing prefix
            List <string> suffixWords = new List <string>();

            // Add word to suffix word list
            suffixWords.Add(word);

            foreach (AffixRule rule in SuffixRules.Values)
            {
                foreach (AffixEntry entry in rule.AffixEntries)
                {
                    string tempWord = AffixUtility.RemoveSuffix(word, entry);
                    if (tempWord != word)
                    {
                        if (BaseWords.ContainsKey(tempWord))
                        {
                            if (VerifyAffixKey(tempWord, rule.Name[0]))
                            {
                                TraceWriter.TraceVerbose("Word Found With Base Words: {0}; Suffix Key: {1}", tempWord, rule.Name[0]);
                                return(true); // word found
                            }
                        }

                        if (rule.AllowCombine)
                        {
                            // saving word to check if it is a word after prefix is removed
                            suffixWords.Add(tempWord);
                        }
                        else
                        {
                            // saving possible base words for use in generating suggestions
                            PossibleBaseWords.Add(tempWord);
                        }
                    }
                }
            }
            // saving possible base words for use in generating suggestions
            PossibleBaseWords.AddRange(suffixWords);

            // Step 4 Remove Prefix, Search BaseWords
            foreach (AffixRule rule in PrefixRules.Values)
            {
                foreach (AffixEntry entry in rule.AffixEntries)
                {
                    foreach (string suffixWord in suffixWords)
                    {
                        string tempWord = AffixUtility.RemovePrefix(suffixWord, entry);
                        if (tempWord != suffixWord)
                        {
                            if (BaseWords.ContainsKey(tempWord))
                            {
                                if (VerifyAffixKey(tempWord, rule.Name[0]))
                                {
                                    TraceWriter.TraceVerbose("Word Found With Base Words: {0}; Prefix Key: {1}", tempWord, rule.Name[0]);
                                    return(true); // word found
                                }
                            }

                            // saving possible base words for use in generating suggestions
                            PossibleBaseWords.Add(tempWord);
                        }
                    } // suffix word
                }     // prefix rule entry
            }         // prefix rule
            // word not found
            TraceWriter.TraceVerbose("Possible Base Words: {0}", PossibleBaseWords.Count);
            return(false);
        }