8

我正在尝试从字符串中解析 C# 中的化学式(格式,例如:Al2O3orO3Cor C11H22O12)。除非特定元素只有一个原子(例如 中的氧原子H2O),否则它可以正常工作。我该如何解决这个问题,此外,有没有比我现在更好的方法来解析化学式字符串?

ChemicalElement 是表示化学元素的类。它具有 AtomicNumber (int)、Name (string)、Symbol (string) 属性。ChemicalFormulaComponent 是表示化学元素和原子数(例如,公式的一部分)的类。它具有 Element (ChemicalElement)、AtomCount (int) 属性。

其余的应该足够清楚以理解(我希望),但如果我能澄清任何事情,请在您回答之前通过评论告诉我。

这是我当前的代码:

    /// <summary>
    /// Parses a chemical formula from a string.
    /// </summary>
    /// <param name="chemicalFormula">The string to parse.</param>
    /// <exception cref="FormatException">The chemical formula was in an invalid format.</exception>
    public static Collection<ChemicalFormulaComponent> FormulaFromString(string chemicalFormula)
    {
        Collection<ChemicalFormulaComponent> formula = new Collection<ChemicalFormulaComponent>();

        string nameBuffer = string.Empty;
        int countBuffer = 0;

        for (int i = 0; i < chemicalFormula.Length; i++)
        {
            char c = chemicalFormula[i];

            if (!char.IsLetterOrDigit(c) || !char.IsUpper(chemicalFormula, 0))
            {
                throw new FormatException("Input string was in an incorrect format.");
            }
            else if (char.IsUpper(c))
            {
                // Add the chemical element and its atom count
                if (countBuffer > 0)
                {
                    formula.Add(new ChemicalFormulaComponent(ChemicalElement.ElementFromSymbol(nameBuffer), countBuffer));

                    // Reset
                    nameBuffer = string.Empty;
                    countBuffer = 0;
                }

                nameBuffer += c;
            }
            else if (char.IsLower(c))
            {
                nameBuffer += c;
            }
            else if (char.IsDigit(c))
            {
                if (countBuffer == 0)
                {
                    countBuffer = c - '0';
                }
                else
                {
                    countBuffer = (countBuffer * 10) + (c - '0');
                }
            }
        }

        return formula;
    }
4

4 回答 4

11

我使用正则表达式重写了您的解析器。正则表达式非常适合您正在做的事情。希望这可以帮助。

public static void Main(string[] args)
{
    var testCases = new List<string>
    {
        "C11H22O12",
        "Al2O3",
        "O3",
        "C",
        "H2O"
    };

    foreach (string testCase in testCases)
    {
        Console.WriteLine("Testing {0}", testCase);

        var formula = FormulaFromString(testCase);

        foreach (var element in formula)
        {
            Console.WriteLine("{0} : {1}", element.Element, element.Count);
        }
        Console.WriteLine();
    }

    /* Produced the following output

    Testing C11H22O12
    C : 11
    H : 22
    O : 12

    Testing Al2O3
    Al : 2
    O : 3

    Testing O3
    O : 3

    Testing C
    C : 1

    Testing H2O
    H : 2
    O : 1
        */
}

private static Collection<ChemicalFormulaComponent> FormulaFromString(string chemicalFormula)
{
    Collection<ChemicalFormulaComponent> formula = new Collection<ChemicalFormulaComponent>();
    string elementRegex = "([A-Z][a-z]*)([0-9]*)";
    string validateRegex = "^(" + elementRegex + ")+$";

    if (!Regex.IsMatch(chemicalFormula, validateRegex))
        throw new FormatException("Input string was in an incorrect format.");

    foreach (Match match in Regex.Matches(chemicalFormula, elementRegex))
    {
        string name = match.Groups[1].Value;

        int count =
            match.Groups[2].Value != "" ?
            int.Parse(match.Groups[2].Value) :
            1;

        formula.Add(new ChemicalFormulaComponent(ChemicalElement.ElementFromSymbol(name), count));
    }

    return formula;
}
于 2010-11-07T07:21:53.480 回答
2

您的方法的问题在这里:

            // Add the chemical element and its atom count
            if (countBuffer > 0)

当您没有数字时,计数缓冲区将为 0,我认为这会起作用

            // Add the chemical element and its atom count
            if (countBuffer > 0 || nameBuffer != String.Empty)

这适用于像 HO2 或类似的公式。formula我相信您的方法永远不会将化学式的 las 元素插入集合中。

您应该在返回结果之前将缓冲区的最后一个元素添加到集合中,如下所示:

    formula.Add(new ChemicalFormulaComponent(ChemicalElement.ElementFromSymbol(nameBuffer), countBuffer));

    return formula;
}
于 2010-11-07T07:22:30.007 回答
1

首先:我没有在 .net 中使用过解析器生成器,但我很确定你能找到合适的东西。这将允许您以更易读的形式编写化学公式的语法。例如,请参阅此问题作为第一个开始。

如果你想保持你的方法:无论它是否有数字,你是否有可能不添加最后一个元素?您可能希望运行循环,i<= chemicalFormula.Length如果i==chemicalFormula.Length还添加您拥有的内容到您的公式中。然后,您还必须删除您的if (countBuffer > 0)条件,因为 countBuffer 实际上可以为零!

于 2010-11-07T07:24:02.723 回答
0

Regex should work fine with simple formula, if you want to split something like:

(Zn2(Ca(BrO4))K(Pb)2Rb)3

it might be easier to use the parser for it (because of compound nesting). Any parser should be capable of handling it.

I spotted this problem few days ago I thought it would be good example how one can write grammar for a parser, so I included simple chemical formula grammar into my NLT suite. The key rules are -- for lexer:

"(" -> LPAREN;
")" -> RPAREN;

/[0-9]+/ -> NUM, Convert.ToInt32($text);
/[A-Z][a-z]*/ -> ATOM;

and for parser:

comp -> e:elem { e };

elem -> LPAREN e:elem RPAREN n:NUM? { new Element(e,$(n : 1)) }
      | e:elem++ { new Element(e,1) }
      | a:ATOM n:NUM? { new Element(a,$(n : 1)) }
      ;
于 2013-11-13T14:51:22.067 回答