[英]calculate molecular weight based on chemical formula using python
I am using python 2.7. 我正在使用python 2.7。
For example my formula is C6H12O6
. 例如,我的公式是C6H12O6
。 I used this code below 我在下面使用了这段代码
formula='C6H12O6'
s = re.findall('([A-Z][a-z]?)([0-9]*)', formula)
and got this result: 并得到以下结果:
s= [('C', '6'), ('H', '12'), ('O', '6')]
From here, I'm trying to figure out how to do this: 从这里,我试图弄清楚如何做到这一点:
( C x 6 )+( H x 12 )+( O x 6 )
Can somebody help please, I've been stuck here for almost a day. 有人可以帮忙吗,我已经待在这里将近一天了。 I also appreciate any other ideas. 我也很感谢其他想法。
You can create a dictionary of weights that map the character of the element to their respective atomic weights, and use the sum()
function to do a summation of the list values you have. 您可以创建一个权重字典,将元素的字符映射到它们各自的原子权重,并使用sum()
函数对您拥有的列表值进行求和。
weights = {'C': 12, 'H': 1, 'O': 16}
s = [('C', '6'), ('H', '12'), ('O', '6')]
total = sum((weights[e] * int(i)) for e, i in s) # 180
This should work, just get a more complete dictionary (the periodic table) for the entire elem_weight 这应该可行,只是获得整个elem_weight的更完整的字典(元素周期表)
import re
formula='CH12O6' #example molecule with singular element
s = re.findall('([A-Z][a-z]?)([0-9]*)', formula)
elem_weight = {'C': 12, 'H': 1, 'O': 16}
total_weight = 0
for elem, count in s:
#For singular elements
if count=='':
count = 1
total_weight += int(count)*elem_weight[elem]
print total_weight
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.