Break a string into list items based on keywords

I am trying to create a function (in Python) that takes its contribution (chemical formula) and breaks down into a list. For example, if the input was "HC2H3O2", it would turn it into:

molecule_list = ['H', 1, 'C', 2, 'H', 3, 'O', 2]

This works well so far, but if I put in an element with two letters, for example sodium (Na), it would split it into:

['N', 'a']

I am looking for a way to get my function to scan a string for keys found in a dictionary called elements. I am also considering using regex for this, but I'm not sure how to implement it. This is my function right now:

def split_molecule(inputted_molecule):
    """Take the input and split it into a list
    eg: C02 => ['C', 1, 'O', 2]
    """
    # step 1: convert inputted_molecule to a list
    # step 2a: if there are two periodic elements next to each other, insert a '1'
    # step 2b: if the last element is an element, append a '1'
    # step 3: convert all numbers in list to ints

    # step 1:
    # problem: it splits Na into 'N', 'a'
    # it needs to split by periodic elements
    molecule_list = list(inputted_molecule)

    # because at most, the list can double when "1" is inserted
    max_length_of_molecule_list = 2*len(molecule_list)
    # step 2a:
    for i in range(0, max_length_of_molecule_list):
        try:
            if (molecule_list[i] in elements) and (molecule_list[i+1] in elements):
                molecule_list.insert(i+1, "1")
        except IndexError:
            break
    # step2b:     
    if (molecule_list[-1] in elements):
        molecule_list.append("1")

    # step 3:
    for i in range(0, len(molecule_list)):
        if molecule_list[i].isdigit():
            molecule_list[i] = int(molecule_list[i])

    return molecule_list
+5
source share
3 answers

What about

import re
print re.findall('[A-Z][a-z]?|[0-9]+', 'Na2SO4MnO4')

result

['Na', '2', 'S', 'O', '4', 'Mn', 'O', '4']

Regex explained:

Find everything that is either

    [A-Z]   # A,B,...Z, ie. an uppercase letter
    [a-z]   # followed by a,b,...z, ie. a lowercase latter
    ?       # which is optional
    |       # or
    [0-9]   # 0,1,2...9, ie a digit
    +       # and perhaps some more of them

, "", "Xy". , [A-Z][a-z]? , |, Ba|Na|Mn...|C|O

, , -

  8(NH4)3P4Mo12O40 + 64NaNO3 + 149NH4NO3 + 135H2O

, . pyparsing ( " " "" ). !

+4

:

[A-Z][a-z]*|\d+

re.findall, , .

:

molecule = 'NaHC2H3O2'
print re.findall(r'[A-Z][a-z]*|\d+', re.sub('[A-Z][a-z]*(?![\da-z])', r'\g<0>1', molecule))

:

['Na', '1', 'H', '1', 'C', '2', 'H', '3', 'O', '2']

sub a 1 , .

+2

, , , , :

import string

formula = 'HC2H3O2Na'
m_list = list()
for x in formula:
   if x in string.lowercase:
      m_list.append(formula[formula.index(x)-1]+x)
      _ = m_list.pop(len(m_list)-2)
   else:
      m_list.append(x)
print m_list
['H', 'C', '2', 'H', '3', 'O', '2', 'Na']
0

All Articles