7
$\begingroup$

Say I have a compound Fe3O4, and I want to separate the name of elements and number. The code I write for separate number is

atomicMassAlloys[Alloy_String] := StringCases[Alloy, DigitCharacter]

But I do not know how to separate the name of element

$\endgroup$
1
  • $\begingroup$ Related: (3443) $\endgroup$
    – Mr.Wizard
    Jan 24, 2016 at 3:49

2 Answers 2

8
$\begingroup$

Here is an example of how to work with chemicals the Mathematica way. First we retrieve the entity corresponding to the chemical:

Mathematica graphics

Then, if we don't know them by heart, we check out the available properties for chemicals:

EntityProperties["Chemical"]

This returns a long list of properties. There is one called "element counts" that seems interesting. We try that one:

Mathematica graphics

$\endgroup$
1
  • 2
    $\begingroup$ Although it answers the question as posed, I'm not sure that this is the best approach. There are an infinite number of chemical compounds, and Mathematica certainly can't recognise them all. In particular, alloys are often non-stoichiometric and do not really make sense to consider as a single chemical substance: the formula is just a sort of average composition. Even for another fairly simple inorganic chemical, let's say cadmium pyrovanadate, I suspect that this method will fail. (But I wasn't able to test it, unfortunately.) $\endgroup$ Jan 24, 2016 at 14:54
8
$\begingroup$

An attempt at a purely string-processing approach:

elem = Alternatives @@ 
   Reverse @ SortBy[StringLength] @ Array[ElementData[#, "Symbol"] &, 112];

chem = StringCases[#, e : elem ~~ n : DigitCharacter ... :> {e, n}] /. "" -> "1" &;

chem @ {"Fe3O4", "CH3Cl"}
{{{"Fe", "3"}, {"O", "4"}}, {{"C", 1}, {"H", "3"}, {"Cl", "1"}}}
$\endgroup$
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.