如何用Python的re模块生成有序列表以计算分子原子量?
分子式原子量计算:提取原子与对应数量的解决方案
你当前的代码仅提取了原子,但未关联每个原子对应的数量,解决核心是用正则表达式同时捕获原子符号和其右侧的数字,再逐一计算累加。
修正后的完整实现
import re from chemistry import Element # 按实际chemistry模块API调整导入 def mol_weight(molecule): total_weight = 0 # 正则分组:匹配原子符号(大写开头+可选小写) + 可选数字 atom_matches = re.findall(r"([A-Z][a-z]?)(\d*)", molecule) for atom_symbol, count_str in atom_matches: # 处理数量:无数字时默认1,有数字则转为整数 atom_count = int(count_str) if count_str else 1 # 获取原子量(根据chemistry模块实际方法调整) atomic_weight = Element(atom_symbol).atomic_weight # 累加计算总原子量 total_weight += atomic_weight * atom_count return total_weight
关键说明
- 正则表达式逻辑:
r"([A-Z][a-z]?)(\d*)"分为两个分组:- 第一个分组
([A-Z][a-z]?):匹配标准原子符号(如C、O、Na),确保大写开头,可选后续小写字母 - 第二个分组
(\d*):匹配原子右侧的数字(可以为空,对应数量为1的情况)
- 第一个分组
- 数量处理:通过三元表达式判断,空字符串转1,非空则转为整数
- 原子量获取:根据你使用的
chemistry模块实际API调整,若模块方法不同(如get_atomic_weight(atom_symbol)),替换对应代码即可
测试示例
print(mol_weight("H2O")) # 输出约18.015 print(mol_weight("CO2")) # 输出约44.01 print(mol_weight("SO4")) # 输出约96.06
内容的提问来源于stack exchange,提问作者Pabloflopygame
相关产品推荐
相关产品推荐

