Python:化学元素计数器 [英] Python: chemical elements counter

查看:52
本文介绍了Python:化学元素计数器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取给定混合物的元素.例如,由dict给出的空气(O2和N2)和己烷(C6H14)的混合物及其各自的摩尔数

I want to get the elements for a given mixture. For examples, for a mixsture of Air (O2 and N2) and Hexane (C6H14) given by the dict with their respectives mole numbers

mix = {'O2': 1, 'N2': 3.76, 'C6H14': 0.01}

我想得到以下内容:

{O: 2, N: 7.52, C:0.06, H: 0.14}

另一个例子:

mix = {'C6H14': 1, 'C9H20': 1}

必须产量

{H: 34, C: 15}
enter code here

字典的顺序并不重要.我正在尝试re.split,但没有任何进展.如果有人可以帮助我,我将不胜感激.

The sequence of the dict it's not important. I was trying with the re.split, but I don't get any progress. If anyone can help me I will be grateful.

编辑:也许我不清楚我的问题,但我想计算的是混合物中的原子数.我尝试使用正则表达式库中的re.findall.我试图将数字与其他字符分开.示例:

Edit: Hi, perhaps I wasn't clear in my question but what I want is to count the number of atoms in a mixture. I tryied to use the re.findall from the regular expressions library. I tried to separate the numbers from the another characters. Example:

mix  = {'C6H14': 1, 'C9H20': 1}
atmix = []
mix = {'O2': 1, 'N2': 3.76, 'C6H14': 0.01}
for x in mix.keys():
    tmp = re.findall(r'[A-Za-z]+|\d+', x)
    tmp = list(zip(tmp[0::2], tmp[1::2]))
    atmix.append(tmp)

我知道:

>>> atmix
[(['O'], ['2']), (['N'], ['2']), (['C', 'H'], ['6', '14'])]

这是包含该物质及其原子数的元组的列表.从这里开始,我需要获取每种物质,并将其与原子数乘以混合字典给出的摩尔数相关联,但是我不知道该怎么做.我试图从混合物中分离出物质及其原子的方法似乎很愚蠢.我需要一种更好的方法来对这些物质及其原子进行分类,并发现如何将其与摩尔数联系起来.

This is a list with tuples of the substances and their numbers of atoms. From here, I need to get each substance and relate with the number of atoms multiplied by the number of mols given by the mix dictionary, but I don't know how. The way I'm trying to separate the substances and their atoms from the mixture seems dumb. I need a better way to classify these substances and their atoms and discover how to relate it with the number of moles.

预先感谢

推荐答案

在使用精心设计的正则表达式将每个元素从其计数中分离出来的同时,您可以遍历 mix 字典.

You can iterate over the mix dict while using a carefully-crafted regex to separate each element from its count.

import re
from collections import defaultdict

mix = {'O2': 1, 'N2': 3.76, 'C6H14': 0.01}
out = defaultdict(float)
regex = re.compile(r'([A-Z]+?)(\d+)?')

for formula, value in mix.items():
    for element, count in regex.findall(formula):
        count = int(count) if count else 1  # supporting elements with no count,
                                            # eg. O in H2O
        out[element] += count * value

print(out)

输出

defaultdict(<class 'float'>, {'O': 2.0, 'N': 7.52, 'C': 0.06, 'H': 0.14})

这篇关于Python:化学元素计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆