|
发表于 2017-6-8 17:02:29
|
显示全部楼层
- import re
- from collections import Counter
- def parse_molecule(exp):
- ptns=[re.compile(r'\{([^{}]+)\}(\d+)'),
- re.compile(r'\[([^\[\]]+)\](\d+)'),
- re.compile(r'\(([^()]+)\)(\d+)'),
- re.compile(r'([A-Z][a-z]?)(\d+)')]
- repl=lambda m: m.group(1) * int(m.group(2))
- for ptn in ptns:
- while ptn.search(exp):
- exp=ptn.sub(repl,exp)
- exp=re.sub(r'[{}\[\]()]','',exp)
- exp=re.sub(r'([A-Z][a-z]?)',r'\1 ',exp).split()
- return dict(Counter(exp))
- exp=('H2O','Mg(OH)2','K4[ON(SO3)2]2','(C5H5)Fe(CO)2CH3',
- 'As2{Be4C5[BCo3(CO2)3]2}4Cu5','{[Co(NH3)4(OH)2]3Co}(SO4)3')
- for e in exp:
- print('%s\n%s\n'%(e,parse_molecule(e)))
复制代码
- H2O
- {'H': 2, 'O': 1}
- Mg(OH)2
- {'H': 2, 'Mg': 1, 'O': 2}
- K4[ON(SO3)2]2
- {'S': 4, 'O': 14, 'K': 4, 'N': 2}
- (C5H5)Fe(CO)2CH3
- {'H': 8, 'C': 8, 'Fe': 1, 'O': 2}
- As2{Be4C5[BCo3(CO2)3]2}4Cu5
- {'As': 2, 'C': 44, 'Co': 24, 'Be': 16, 'B': 8, 'Cu': 5, 'O': 48}
- {[Co(NH3)4(OH)2]3Co}(SO4)3
- {'H': 42, 'Co': 4, 'N': 12, 'S': 3, 'O': 18}
复制代码 |
|