[Tutor] parsing chemical formula

Tim Wilson wilson@chemsun.chem.umn.edu
Mon, 29 Mar 1999 00:23:35 -0600 (CST)


Greetings all:

I'd like to write a small Python app to act as a command line molecular
weight calculator. I'm a Python beginner, and I'm still in the planning
stage on this one. Specifically, I'd like to get some expert opinions on
the best way to parse the chemical formula to extract the type and number
of atoms. An example (and chemistry refresher):

H2SO4 contains 2 H, 1 S, 4 O atoms
Mg(NO3)2 contains 1 Mg, 2 N, 6 O atoms (watch those parentheses!)

Ideally, the user would run the program like this:

$ molwt H2O
The molecular weight of H2O is 18.02 g/mol.
$

I've constructed a dictionary containing all of the element symbols and
molecular weights. What type of data structure would be most appropriate
for temporarily holding the number and type of atoms in the formula before
the total mol. weights is calculated?

Any other suggestions? I think this might be a nice little app that could
be very useful.

-Tim
(At least that's what some people call me.)

--
Timothy D. Wilson			"A little song, a little dance,
University of MN, chem. dept.		a little seltzer down your 
wilson@chem.umn.edu			pants."   -Chuckles the Clown
Phone: (612) 625-9828                       as eulogized by Ted Baxter