【问题标题】:How to ignore a specific character in a string, and later use it?如何忽略字符串中的特定字符,然后再使用它?
【发布时间】:2020-06-19 00:53:22
【问题描述】:

之前我问过一个问题,关于如何根据大写字母或空格分隔字符串中的字符。它立即得到了答复。处理同一段代码,现在我想知道是否可以读取输入并忽略整数,然后再使用它。

例如如果字符串是H2O,将H的值乘以两次,然后加上O的值。

How to read two characters from an input string?

^^如果有用的话,这是我在相同代码上提出的上一个问题的链接。

import re

atomMass_Table = {'H': 1.00797, 'He': 4.00260, 'B': 10.81,'C': 12.011, 'N': 14.067, 'O': 15.9994,'F': 
18.998403,'P': 30.97376, 'S': 32.06, 'K':39.0983, ' ': 0, None: 0}

TotalMass=0
elements=[ ]

mol=input("Enter a molecule:")

elements = re.findall('[A-Z][^A-Z]*', mol)
for a in elements:
    if a == int:
       element=None
       atomicMass=atomMass_Table.get(a)
       TotalMass=TotalMass+atomicMass
print (TotalMass)

希望我不会太困惑 :)

【问题讨论】:

  • alec的解决方案如何解决多于1位的化学数字,比如糖?

标签: python string input integer character


【解决方案1】:

我扩展了您的请求并为每个分子添加了一个类。

一个类包含三个属性:

  • 原始元素
  • 分子结构
  • 分子质量

可以通过绘制分子或其他特征来扩展该类。

班级:

class molecule:
    def __init__(self, raw_element, atom_mass_table):
        self.amt = atom_mass_table
        self.raw_element = raw_element
        self.molecule_structur = self.get_struc()
        self.molecule_mass = self.cal_mass()

    def get_struc(self):
        return [self._split_nodes(e) for e in self._split_in_nodes()]

    def cal_mass(self):
        sum = 0
        for i in self.molecule_structur:
            sum += self.amt[i[0]] * i[1]
        return sum


    def _split_nodes(self, node):
        s = ""
        n = ""
        for l in node:
            if l.isalpha():
                s += l
            elif l.isdigit():
                n += l
        if n is None:
            n = 1
        return (s, int(n))

    def _split_in_nodes(self):
        new_el = [e.isupper() for e in self.raw_element]
        el_str = []
        pos = 0
        for _ in range(sum(new_el)):
            if True in new_el[pos+1:]:
                end = pos + new_el[pos+1:].index(True)+1
            else:
                end = len(new_el)
            el_str.append(self.raw_element[pos:end])
            pos = end
        return el_str

类只需要:

  • 原始元素描述 - C12H22O11
  • 您提供的 atom_mass_table - 我没有将它包含在课程中,以便以后扩展。

所以要测试代码:

if __name__ == "__main__":

    element = input("Please enter your Molecule: ")

    molecule = Molecule(element, atom_mass_table)
    print(molecule.molecule_structur)
    print(molecule.molecule_mass)

输入:

Please enter you Molecule:  C32H128O64

输出:

[('C', 32), ('H', 128), ('O', 64)]
1537.33376

希望对您有所帮助,当您进一步改进此应用程序时,您可以邀请我加入您的 GitHub 项目。

【讨论】:

  • @Toby 你可以给我反馈这个选项。我认为它最适合更大的项目。
  • 对不起,它没有通知我,我认为这是一个很好的解决方案。但是为了让它变得完美,另一个功能如何让用户将他们需要的原子权重放入字典并写下一个json,这样你就不需要每次调用这个类时都列出表格
【解决方案2】:

有两种解决方案适合您。我不明白 Thomas 的解决方案,但 alec 的解决方案是可以接受的。但是,如果您有“C12H22O11”之类的东西,它就无法工作。我给出一个可以解决的方案,看看吧。

atomMass_Table = {'H': 1.00797, 'He': 4.00260, 'B': 10.81,'C': 12.011, 'N': 14.067, 

'O': 15.9994,'F': 18.998403,'P': 30.97376, 'S': 32.06, 'K':39.0983, ' ': 0, None: 0, 'd': 0}

TotalMass=0
elements=[ ]

mol=input("Enter a molecule:")
if not mol[-1].isdigit():
    mol += '1'
mol += 'd'
number = []

for a in mol:

    if a.isdigit():
       number.append(a)
    else:
        if not number:
            value = atomMass_Table.get(a)

        else:
            TotalMass += value * int(''.join(number))
            value = atomMass_Table.get(a)
            number = []
print (TotalMass)

H2O 的解是 18.01534,C12H22O11 是 342.30074。 希望对您有所帮助!

【讨论】:

    【解决方案3】:

    使用isalpha() 检查元素是否只包含字母。如果没有,你可以使用字符串切片从字典中获取第一个字符的值,然后乘以第二个字符。

    atomMass_Table = {'H': 1.00797, 'He': 4.00260, 'B': 10.81,'C': 12.011, 'N': 14.067, 'O': 15.9994,'F': 
    18.998403,'P': 30.97376, 'S': 32.06, 'K':39.0983, ' ': 0, None: 0}
    
    TotalMass = 0
    mol = input("Enter a molecule: ")
    elements = re.findall('[A-Z][^A-Z]*', mol)
    
    for a in elements:
        if a.isalpha():
            TotalMass += atomMass_Table.get(a)
        else:
            TotalMass += atomMass_Table.get(a[0]) * int(a[1])
    print(TotalMass)
    

    例子:

    Enter a molecule: H2O
    18.01534
    >>> 
    

    【讨论】:

      【解决方案4】:

      这个怎么样?

      import re
      
      atom_masses = {'H': 1.00797, 'He': 4.00260, 'B': 10.81, 'C': 12.011, 'N': 14.067, 'O': 15.9994, 'F':
          18.998403, 'P': 30.97376, 'S': 32.06, 'K': 39.0983, ' ': 0, None: 0}
      
      total_mass = 0
      elements = []
      
      mol = input("Enter a molecule:")
      
      parts = re.findall('([A-Z][a-z]?)(\d)*', mol)
      print(parts)
      for element, count in parts:
          if count == '':
              count = 0
          atomic_mass = atom_masses.get(element)
          total_mass = total_mass + atomic_mass * float(count)
      print (total_mass)
      

      我更改了正则表达式以将字符串分成单独的原子及其计数。它必须是一个大写字母,后跟一个可选的小写字母和一个可选的数字。

      另外,我更改了变量名,因为它们应该是小写字母。

      【讨论】:

      • @Toby,你不明白什么?
      • @Toby,如果我尝试您的解决方案,它不适用于“他”。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-08
      • 2014-09-13
      • 2018-09-27
      • 1970-01-01
      • 2021-08-27
      • 2021-11-18
      • 1970-01-01
      相关资源
      最近更新 更多