Tôi đang cố tạo hàm (bằng Python) lấy đầu vào của nó (công thức hóa học) và tách thành một danh sách. Ví dụ, nếu đầu vào là "HC2H3O2", nó sẽ biến nó thành:Tách chuỗi thành các phần tử danh sách dựa trên từ khóa
molecule_list = ['H', 1, 'C', 2, 'H', 3, 'O', 2]
này, hoạt động tốt cho đến nay, nhưng nếu tôi nhập vào một phần tử với hai chữ cái trong nó, ví dụ natri (Na) , nó sẽ chia thành:
['N', 'a']
Tôi đang tìm cách để thực hiện chức năng của mình thông qua chuỗi khóa tìm thấy trong từ điển được gọi là phần tử. Tôi cũng đang xem xét sử dụng regex cho điều này, nhưng tôi không chắc chắn làm thế nào để thực hiện nó. Đây là những gì chức năng của tôi là ngay bây giờ:
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
Đó là rực rỡ, cảm ơn bạn! Bạn có thể giải thích về regex không? – ohblahitsme
Còn về 'Ca (HCOO) 2' thì sao? –
+1 để đề cập rằng bạn sẽ cần một trình phân tích cú pháp thực, thay vì một trình phân tích cú pháp regex – aitchnyu