我想用Python改进我的代码。我在这里寻找一个逻辑帮助,以便用更少的代码获得相同的结果。
我的过程通过参数获取一个原子字符串,并“学习”它们,返回已学习的原子列表。
我想知道是否有任何方法可以优化我的代码。
def mol_term(molecule):
upper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
list_of_atoms = []
for i in range(len(molecule) - 1): #goes all string long
if molecule[i] in upper:
if not molecule[i+1] in upper:
temp = molecule[i] + molecule[i+1] #if atom has two letters
i = i + 1
else:
temp = molecule[i] #if not
if not temp in list_of_atoms:
list_of_atoms.append(temp) #if atom is not in the list appends to it
if molecule[-1] in upper:
list_of_atoms.append(molecule[-1]) #checks last letter
return print(list_of_atoms)非常感谢。
发布于 2013-09-26 17:01:30
您正在寻找一个正则表达式,它捕获一个大写字符,后面跟着一个可选的低位字符。
list(set(re.findall('[A-Z][a-z]?', 'CuBDa')))但您可能忽略了数字,即CO2,这将会做到这一点
re.findall('[A-Z][a-z]?[0-9]*', 'C4H10FO2P')如果您只想忽略这些数字,则可以使用第一个表达式
发布于 2013-09-26 17:04:24
这应该能起到作用
import re
molecule = 'CH3COOH'
print set(re.findall('[A-Z][a-z]?',molecule))它将打印:
set(['H', 'C', 'O'])发布于 2013-09-26 17:18:21
我建议您查看Python PLY文档,并查看Andrew Dalke的示例,以获取使用分子进行解析的示例。(http://www.dalkescientific.com/writings/NBN/parsing_with_ply.html)
您可以使用原子符号和该原子/符号在分子中出现的时间来定义标记,例如,对于像CH3COOH (乙酸)这样的分子。
import lex
tokens = (
"SYMBOL",
"COUNT"
)
t_SYMBOL = (
r"C[laroudsemf]?|Os?|N[eaibdpos]?|S[icernbmg]?|P[drmtboau]?|"
r"H[eofgas]?|A[lrsgutcm]|B[eraik]?|Dy|E[urs]|F[erm]?|G[aed]|"
r"I[nr]?|Kr?|L[iaur]|M[gnodt]|R[buhenaf]|T[icebmalh]|"
r"U|V|W|Xe|Yb?|Z[nr]"
)
def t_COUNT(t):
r"\d+"
t.value = int(t.value)
return t
lex.lex()
lex.input("CH3COOH")
for tok in iter(lex.token, None):
print repr(tok.type), repr(tok.value)当我运行代码时,我得到以下代码
'SYMBOL‘'C’'SYMBOL‘'H’'COUNT‘3 'SYMBOL’'C‘'SYMBOL’'O‘'SYMBOL’'O‘’
更多信息请点击此处http://www.dabeaz.com/ply/
https://stackoverflow.com/questions/19023643
复制相似问题