나는 입력 (화학 공식)을 받아서 목록으로 나눠주는 함수 (파이썬에서)를 만들려고한다. 입력이 "HC2H3O2"인 경우 예를 들어, 그것으로 바꿀 것 :문자열을 키워드를 기반으로 목록 요소로 바꾼다
molecule_list = ['H', 1, 'C', 2, 'H', 3, 'O', 2]
이 지금까지 잘 작동하지만 입력하면 예를 들어 나트륨에 대한 그것의 두 글자와 요소 (나)
['N', 'a']
요소라는 사전에있는 키의 문자열을 통해 내 함수를 살펴 보는 방법을 찾고 있습니다. 나는 또한 이것에 대한 정규식을 사용하여 고려 중이 야,하지만 그것을 구현하는 방법을 잘 모르겠습니다.
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 당신이 정규 파서 대신 실제 파서가 필요하다는 것을 언급하기 위해 +1 – aitchnyu