예제 #1
0
        public void EvaluateReplaceCharacterTestcountryCode()
        {
            Object[]       os        = { "+4412345678", "+44", "0", "," };
            Object         expResult = "012345678";
            CustomFunction Instance  = new ReplaceCharacters();
            Object         result    = Instance.Evaluate(null, os);

            Assert.AreEqual(expResult, result);
        }
예제 #2
0
        public void EvaluateReplaceCharacterTest()
        {
            Object[]       os        = { "(1234)-[567+8]", "[,],+,-,(,)", "", "," };
            Object         expResult = "12345678";
            CustomFunction Instance  = new ReplaceCharacters();
            Object         result    = Instance.Evaluate(null, os);

            Assert.AreEqual(expResult, result);
        }
        /// <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;
        }
예제 #4
0
        public static int Brackets(string S)
        {
            int properlyNested = 0;

            try
            {
                if (S == null)
                {
                    Console.WriteLine("Unhandled 'case': S is null.");
                    return(properlyNested);
                }
                if (S == "")
                {
                    properlyNested = 1;
                }
                else
                {
                    ReplaceCharacters ReplaceOpeningAndClosing = (s, indices, c) =>
                    {
                        string rs = s;

                        try
                        {
                            rs = new string(
                                rs.Select((cc, kk) =>
                            {
                                char newChar = cc;
                                foreach (int ijk in indices)
                                {
                                    if (kk == ijk)
                                    {
                                        newChar = c;
                                    }
                                }

                                return(newChar);
                            }
                                          ).ToArray());
                        }
                        catch (Exception ex)
                        {
                            System.Console.WriteLine("Brackets:ReplaceOpeningAndClosing " + ex.Message);
                        }

                        return(rs);
                    };

                    /// returns (opening index, closing index) dictionary
                    /// If no partner is available -1 is as value or a negative key
                    IsPossiblyNested PossiblyNested = (ss) =>
                    {
                        IDictionary <int, int> partners = new Dictionary <int, int>();

                        try
                        {
                            string s = (string)ss.Clone(); // new string(ss);

                            Stack <int> openings = new Stack <int>();
                            IList <int> closings = new List <int>();
                            var         matches  = Regex.Matches(s, @"[\{\[\(\}\]\)]");
                            foreach (Match m in matches)
                            {
                                int index = m.Index;
                                switch (s[index])
                                {
                                case '{': openings.Push(index); break;

                                case '[': openings.Push(index); break;

                                case '(': openings.Push(index); break;

                                case '}': closings.Add(index); break;

                                case ']': closings.Add(index); break;

                                case ')': closings.Add(index); break;
                                }
                            }

                            //foreach (var o in openings) Console.WriteLine($"{ss[o]} => {ss}");
                            //foreach (var c in closings) Console.WriteLine($"{ss[c]} => {ss}");

                            int count = openings.Count;
                            for (int i = 0; i < count; i++)
                            {
                                if (openings.Count == 0)
                                {
                                    break;
                                }
                                int    idx     = openings.Pop();
                                string opening = ss[idx].ToString();
                                foreach (int j in closings)
                                {
                                    string closing = null;
                                    switch (ss[idx])
                                    {
                                    case '{': closing = "}"; break;

                                    case '[': closing = "]"; break;

                                    case '(': closing = ")"; break;
                                    }
                                    bool theyMatch = ss[j].ToString() == closing;
                                    if (j > idx && theyMatch)
                                    {
                                        string u = s.Substring(idx + 1, j - idx - 1);
                                        //Console.WriteLine($"{idx} #{u}# {j} => $${s}$$");
                                        if (!string.IsNullOrEmpty(u))
                                        {
                                            var m  = Regex.Match(u, Regex.Escape(opening));
                                            var mm = Regex.Match(u, Regex.Escape(closing));
                                            if (!m.Success && !mm.Success)
                                            {
                                                if (1 == Brackets(u))
                                                {
                                                    partners.Add(idx, j);
                                                    int[] indices = new int[] { idx, j };
                                                    s = ReplaceOpeningAndClosing(s, indices, ' ');
                                                    //Console.WriteLine("String: " + s);
                                                    closings.Remove(j); // It makes sense due to the next break
                                                    break;
                                                }
                                            }
                                        }
                                        else
                                        {
                                            partners.Add(idx, j);
                                            int[] indices = new int[] { idx, j };
                                            s = ReplaceOpeningAndClosing(s, indices, ' ');
                                            //Console.WriteLine("String: " + s);
                                            closings.Remove(j); // It makes sense due to the next break
                                            break;
                                        }
                                    }
                                    else
                                    {
                                        //Console.WriteLine($"{idx} -- {j} => $${s}$$");
                                    }
                                }
                                if (!partners.ContainsKey(idx))
                                {
                                    partners.Add(idx, -1);
                                    int[] indices = new int[] { idx };
                                    s = ReplaceOpeningAndClosing(s, indices, ' ');
                                    //Console.WriteLine("String: " + s);
                                }
                            }
                            // Check closings
                            int cki = -1;
                            foreach (int j in closings)
                            {
                                if (!partners.Values.Contains(j))
                                {
                                    partners.Add(cki, j);
                                    cki -= 1;
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            System.Console.WriteLine("Brackets:PossiblyNested " + ex.Message);
                        }

                        return(partners);
                    };

                    var partnersDico = PossiblyNested(S);
                    properlyNested = 1;
                    foreach (var pk in partnersDico)
                    {
                        //Console.WriteLine($"Opening => Closing: {pk.Key} => {pk.Value} $${S}$$");
                        if (pk.Value == -1 || pk.Key < 0)
                        {
                            properlyNested = 0;
                            break;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Console.WriteLine("Brackets: " + ex.Message);
            }

            return(properlyNested);
        }