简体   繁体   English

使用python根据化学式计算分子量

[英]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.

相关问题 python中蛋白质的分子量总和 - The Sum of molecular weight of proteins in python 为什么在 biopython 中使用 function 来计算蛋白质的分子量与我在 python 中的代码的结果不同 - why bulit in function in biopython to calculate molecular weight of proteins not give me the same result as my code in python (Bio.SeqUtils.molecular_weight 函数)无法计算明确核苷酸序列的分子量 - Inability of (Bio.SeqUtils.molecular_weight function) to calculate molecular weight of unambiguous nucleotide sequence 如何在python中获得化合物的分子量? - How to get molecular weight of a compound in python? 由一串元素 python 形成化学式 - Forming a chemical formula from a string of elements python 使用 Python 中的正态分布计算权重 - Calculate weight using normal distribution in Python BioPython:氨基酸序列包含“ J”,无法计算分子量 - BioPython: Amino acid Sequence contains 'J' and can't calculate the molecular weight 我需要计算蛋白质片段的分子量并将这些值放在一个列表中 - I need to calculate the molecular weight of protein fragments and put those values in a list 使用单个原子求解 python 中的分子结构 - Solve molecular structure in python using individual atoms 使用pyparsing使外部标记在化学式中改变内部标记 - Make outer tokens change inner tokens in a chemical formula using pyparsing
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM