Girişini (bir kimyasal formül) alan ve bir listeye bölen bir işlev (Python'da) oluşturmaya çalışıyorum. giriş "HC2H3O2" ise Örneğin, bu çevirmek olacaktır:Anahtar kelimeleri temel alan liste öğelerine ayırın
molecule_list = ['H', 1, 'C', 2, 'H', 3, 'O', 2]
Bu, şimdiye kadar iyi çalışır, ancak girdi eğer örneğin sodyum içinde iki harf, bir eleman (Na) benim işlevi bir sözlük denilen elemanlar bulunan tuşlar için dize yoluyla görünmesi için bir yol arıyorum
['N', 'a']
: bu bölün olacaktır. Bunun için regex kullanmayı da düşünüyorum, ancak bunu nasıl uygulayacağımı bilmiyorum.
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
parlak Yani, teşekkür ederim! Normal ifadeyi açıklar mısınız? – ohblahitsme
Ya Ca (HCOO) 2' hakkında? Bir regex ayrıştırıcısı yerine gerçek bir ayrıştırıcıya ihtiyacınız olduğunu belirtmek için –
+1 – aitchnyu