Próbuję utworzyć funkcję (w języku Python), która pobiera dane wejściowe (wzór chemiczny) i dzieli się na listę. Na przykład, jeśli sygnał wejściowy jest „HC2H3O2”, to będzie włączyć je do:Przerwij łańcuch na elementy listy na podstawie słów kluczowych
molecule_list = ['H', 1, 'C', 2, 'H', 3, 'O', 2]
To dobrze do tej pory, ale jeśli wejście element z dwoma literami w tym, na przykład, sód (Na) , byłoby podzielić ją na:
['N', 'a']
Szukam sposobu, aby moja funkcja przejrzeć łańcucha kluczy znalezionych w słowniku nazywane elementami. Rozważam również zastosowanie w tym celu wyrażenia regularnego, ale nie jestem pewien, jak go zaimplementować. To właśnie moja funkcja jest teraz:
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
To genialne, dziękuję! Czy mógłbyś wyjaśnić regex? – ohblahitsme
Co z 'Ca (HCOO) 2'? –
+1 za to, że potrzebujesz prawdziwego analizatora składni zamiast edytora regex – aitchnyu