我将创建一个函数(用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