简体   繁体   English

Python:化学元素计数器

[英]Python: chemical elements counter

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例如,对于由字典给出的空气(O2 和 N2)和己烷(C6H14)的混合物及其各自的摩尔数

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

I want to get the following:我想得到以下内容:

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

Another example:另一个例子:

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

must yields必须屈服

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

The sequence of the dict it's not important. dict 的顺序并不重要。 I was trying with the re.split, but I don't get any progress.我正在尝试 re.split,但没有任何进展。 If anyone can help me I will be grateful.如果有人可以帮助我,我将不胜感激。

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.我尝试使用正则表达式库中的 re.findall。 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)

for know i have:知道我有:

>>> 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.我需要一种更好的方法来对这些物质及其原子进行分类,并发现如何将其与摩尔数联系起来。

Thank in advance预先感谢

You can iterate over the mix dict while using a carefully-crafted regex to separate each element from its count.您可以迭代mix字典,同时使用精心设计的正则表达式将每个元素与其计数分开。

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)

outputs产出

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM