下面是我编写的脚本的一部分,其中 if 语句有问题。 如果我想使用 re.match('ATOM|MODEL',lines[i]),我收到错误消息。删除 re.match 中的“|MODEL”,它将起作用。 谁能给我一些提示为什么会发生这种情况?非常感谢!
new_pdb=open(pdb_out,'w')
i=0
while (i<len(lines)):
frag=lines[i].split()
# do not know why 'ATOM|MODEL' does not work
if (re.match('ATOM',lines[i]) and "H" not in frag[2]):
new_pdb.write(lines[i])
i=i+1
new_pdb.close()
下面是我使用 re.match('ATOM|MODEL',lines[i]) 时的错误消息:
回溯(最近一次调用最后一次): 文件“non-h-1.py”,第 17 行,位于 if (re.match('ATOM|MODEL',lines[i]) 且“H”不在 frag[2] 中): IndexError:列表索引超出范围
最佳答案
以 MODEL
开头的行
中至少有一个包含少于三个空格分隔的项目,因此 frag[2]
失败。如果从正则表达式中删除 |MODEL
,re.match()
会失败,因此 Python 甚至不会尝试计算 frag[2]
这就是为什么在这种情况下不会发生错误。
除此之外,您不应该使用 while
循环迭代 lines
- Python 不是 C。使用
for line in lines:
frag = line.split()
if (re.match('ATOM',line) and "H" not in frag[2]):
new_pdb.write(line)
关于python - 重新匹配时出现 IndexError : list index out of range,,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27539792/