如何找到括号并计算化学成分中元素的百分比?
How to find the parentheses and calculate the percentage of elements in a chemical composition?
您好,我正在尝试从化学成分中获取每种元素的百分比。以下代码适用于正常的化学成分。
comp = "Ag20Al25La55"
re.findall('([A-Z][a-z]?)([0-9]*[.]?[0-9]*)', comp)
输出是
[('Ag', '20'), ('Al', '25'), ('La', '55')]
但是我怎样才能得到与括号类似的东西?
comp = "(Cu60Zr40)98Y2"
上面的代码会给出
[('Cu', '60'), ('Zr', '40'), ('Y', '2')]
但正确的输出应该是
[('Cu', '58.8'), ('Zr', '39.2'), ('Y', '2')]
因为我们必须将 98 乘以 60% 才能得到 Cu 的百分比,并将 98 乘以 40% 才能得到 Zr 的百分比。
你可以试试:
def compute(x):
y = float(x.group(2))
return ''.join([i+str(float(j)*y/100) for i,j in re.findall('([A-z]+)(\d+[.]?\d*)', x.group(1))])
def final(x):
cmp = re.sub('(\(.*\))(\d+)', compute, x)
return re.findall('([A-Z][a-z]?)([0-9]*[.]?[0-9]*)', cmp)
final(comp)
[('Cu', '58.8'), ('Zr', '39.2'), ('Y', '2')]
免责声明:这不是最好的方法
您好,我正在尝试从化学成分中获取每种元素的百分比。以下代码适用于正常的化学成分。
comp = "Ag20Al25La55"
re.findall('([A-Z][a-z]?)([0-9]*[.]?[0-9]*)', comp)
输出是
[('Ag', '20'), ('Al', '25'), ('La', '55')]
但是我怎样才能得到与括号类似的东西?
comp = "(Cu60Zr40)98Y2"
上面的代码会给出
[('Cu', '60'), ('Zr', '40'), ('Y', '2')]
但正确的输出应该是
[('Cu', '58.8'), ('Zr', '39.2'), ('Y', '2')]
因为我们必须将 98 乘以 60% 才能得到 Cu 的百分比,并将 98 乘以 40% 才能得到 Zr 的百分比。
你可以试试:
def compute(x):
y = float(x.group(2))
return ''.join([i+str(float(j)*y/100) for i,j in re.findall('([A-z]+)(\d+[.]?\d*)', x.group(1))])
def final(x):
cmp = re.sub('(\(.*\))(\d+)', compute, x)
return re.findall('([A-Z][a-z]?)([0-9]*[.]?[0-9]*)', cmp)
final(comp)
[('Cu', '58.8'), ('Zr', '39.2'), ('Y', '2')]
免责声明:这不是最好的方法