入力(化学式)を受け取り、リストに分割する関数(Pythonで)を作成しようとしています。 入力が「HC2H3O2」だった場合、それはにそれを回すでしょう:キーワードを基にリスト要素に文字列を区切ります
molecule_list = ['H', 1, 'C', 2, 'H', 3, 'O', 2]
これ、今のところうまく動作しますが、たとえば、ナトリウム(Na)のために、それに2つの文字、とI入力要素を場合
要素という辞書にあるキーの文字列を見るための方法を探しています。私はまた、正規表現を使用して検討しているが、私はそれを実装する方法がわからない。これは私の関数は、今あるものである:
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
華麗です、ありがとう!あなたは正規表現を説明してもらえますか? – ohblahitsme
'Ca(HCOO)2'はどうですか? –
+1正規表現パーサーではなく、実際のパーサーが必要であると言及しています – aitchnyu