根据关键字将字符串拆分为列表元素

7

我将创建一个函数(用Python编写),它将接收一个化学式并将其拆分为列表。

例如,如果输入为“HC2H3O2”,则会将其转换为:

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

目前为止,这个有效果。但是,如果我输入一个有两个字母的元素,例如钠(Na),它将被分成:

['N', 'a']

我正在寻找一种方法,使得我的函数能够查找在名为elements的字典中找到的键。我也考虑使用正则表达式来实现这个功能,但我不确定该如何实现。目前我的函数如下:

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
3个回答

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

结果

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

正则表达式解释:

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(记得在“示例”下面勾选“化学公式”)。祝你好运!


太棒了,谢谢!你介意解释一下正则表达式吗? - ohblahitsme
需要一个真正的解析器,而不是一个正则表达式解析器。+1 - Jesvin Jose

2

这样的表达式将匹配所有相关部分:

[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函数会在所有不紧跟数字的原子后添加一个1

1

非正则表达式方法,有点巧妙但可能不是最好的方法,但它能够工作:

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']

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接