【问题标题】:How to find the parentheses and calculate the percentage of elements in a chemical composition?如何找到括号并计算化学成分中元素的百分比?
【发布时间】:2020-11-10 19:43:35
【问题描述】:

您好,我正在尝试从化学成分中获取每种元素的百分比。以下代码适用于正常的化学成分。

comp = "Ag20Al25La55"

re.findall('([A-Z][a-z]?)([0-9]*[.]?[0-9]*)', comp)

输出是

[('Ag', '20'), ('Al', '25'), ('La', '55')]

Bur 我怎样才能得到与括号类似的东西?

comp = "(Cu60Zr40)98Y2"

上面的代码会给出

[('Cu', '60'), ('Zr', '40'), ('Y', '2')]

但正确的输出应该是

[('Cu', '58.8'), ('Zr', '39.2'), ('Y', '2')]

因为我们必须将 98 乘以 60% 才能得到 Cu 的百分比,而将 98 乘以 40% 才能得到 Zr 的百分比。

【问题讨论】:

  • 请不要只给出一些个例子,而是提供你的语法定义。非常重要的是,澄清它是否可以递归/嵌套——例如((Cu60)98Zr40)98 也是一个有效的表达式吗?
  • 这能回答你的问题吗? Parsing pseudo-algebraic string into command
  • 感谢您的评论。 No ((Cu60)98Zr40)98 不是有效的表达式。我给出这个例子是因为其他情况看起来和这个完全一样。没有嵌套案例。只有一对括号。

标签: python python-3.x python-2.7 parsing parentheses


【解决方案1】:

你可以试试:

def compute(x):
  y = float(x.group(2))
  return ''.join([i+str(float(j)*y/100) for i,j in re.findall('([A-z]+)(\\d+[.]?\\d*)', x.group(1))])
  
def final(x): 
    cmp = re.sub('(\\(.*\\))(\\d+)', compute, x)
    return re.findall('([A-Z][a-z]?)([0-9]*[.]?[0-9]*)', cmp)

final(comp)
[('Cu', '58.8'), ('Zr', '39.2'), ('Y', '2')]

免责声明:这不是最好的方法

【讨论】:

  • @HumanLearning 如果可行,您可以接受答案以关闭问题
猜你喜欢
  • 2013-10-28
  • 2014-01-29
  • 1970-01-01
  • 2017-10-07
  • 1970-01-01
  • 1970-01-01
  • 2022-11-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多