【问题标题】:Python function about chemical formulas关于化学式的Python函数
【发布时间】:2022-12-04 00:58:36
【问题描述】:

我有一个包含化学物质名称和一些信息的 CSV 文件。我需要做的是添加新列并写入它们的公式、分子量并计算每个公式中的 H、C、N、O、S 原子数。我被卡住了与计数原子数部分。我有相关的功能,但我不知道如何合并它并使代码工作。

import pandas as pd    
import urllib.request    
import copy    
import re    

df = pd.read_csv('AminoAcids.csv')

def countAtoms(string, dict={}):
    curDict = copy.copy(dict)
    atoms = re.findall("[A-Z]{1}[a-z]*[0-9]*", string)

    for j in atoms:
        atomGroups = re.match('([A-Z]{1}[a-z]*)([0-9]*)', j)
        atom = atomGroups.group(1)
        number = atomGroups.group(2)
        try :
            curDict[atom] = curDict[atom] + int(number)
        except KeyError:
            try :
                curDict[atom] = int(number)
            except ValueError:
                curDict[atom] = 1
        except ValueError:
            curDict[atom] = curDict[atom] + 1
    return curDict

df["Formula"] = ['C3H7NO2', 'C6H14N4O2 ','C4H8N2O3','C4H7NO4 ',
'C3H7NO2S ','C5H9NO4','C5H10N2O3','C2H5NO2 ','C6H9N3O2',
'C6H13NO2','C6H13NO2','C6H14N2O2 ','C5H11NO2S ','C9H11NO2',
'C5H9NO2 ','C3H7NO3','C4H9NO3 ','C11H12N2O2 ','C9H11NO3 ','C5H11NO2']
df["Molecular Weight"] = ['89.09','174.2','132.12',
'133.1','121.16','147.13','146.14','75.07','155.15',
'131.17','131.17','146.19','149.21','165.19','115.13',
'105.09','119.12','204.22','181.19','117.15']
df["H"] = 0
df["C"] = 0
df["N"] = 0
df["O"] = 0
df["S"] = 0
df.to_csv("AminoAcids.csv", index=False)
print(df.to_string()) 

【问题讨论】:

  • 您能否提供 CSV 文件的格式或至少一小段摘录?
  • 一个示例记录的理想输出是什么?
  • 这是一个 excel 文件。它只是一个包含 3-4 列的表格,相应地包含以下信息:化学名称、三个字母、一个字母、极化。我将尝试将该文件添加到问题中
  • 好吧,我需要一个列来计算每个公式中的所有 H 原子数。我需要这个用于每个公式的 C、N、O 和 S 原子

标签: python python-3.x csv chemistry


【解决方案1】:

如果我理解正确的话,你应该可以在这里使用str.extract

df["H"] = df["Formula"].str.extract(r'H(d+)')
df["C"] = df["Formula"].str.extract(r'C(d+)')
df["N"] = df["Formula"].str.extract(r'N(d+)')
df["O"] = df["Formula"].str.extract(r'O(d+)')
df["S"] = df["Formula"].str.extract(r'S(d+)')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    相关资源
    最近更新 更多