【问题标题】:NameError: variable is not defined when searching for a keyword with pythonNameError:使用python搜索关键字时未定义变量
【发布时间】:2021-04-27 15:00:28
【问题描述】:

我正在尝试扫描多个文件并在同一行中搜索两个关键字。我正在尝试在同一行中查找关键字“SEQADV”和“MUTATION”。问题是我不断收到错误“NameError: name 'wt_residue' is not defined”。当我搜索一个关键字“SEQADV”时,程序运行流畅。

        if 'SEQADV' and 'MUTATION' in line:
            try:
                mutation = line.split()
                sequence_number = mutation[4]
                chain = mutation[3]
                mutant_residue = mutation[2]
                wt_residue = mutation[7]
            except IndexError:
                pass

#Prints all data to the .csv file above and closes the file 
            print(",".join([pdb_name, mutant_residue, chain, sequence_number, wt_residue]), file=datafile)    
datafile.close()

【问题讨论】:

  • 这一行是不正确的if 'SEQADV' and 'MUTATION' in line: 如果代码碰到了except 块,wt_residue 也是未声明的
  • except IndexError: pass 是一个非常糟糕的主意。在分配之前,您可能会遇到错误。去掉try,看看有没有报错。
  • 好的。我删除了除 IndexError: pass 之外的内容,但随后我收到另一个错误消息“列表索引超出范围”。请问我该如何解决 if 语句?
  • if 'SEQADV' and 'MUTATION' in line: 等价于if 'MUTATION' in line:'SEQADV' 被评估为布尔表达式,并且在该上下文中始终被评估为 True

标签: python python-3.x csv


【解决方案1】:

尝试将您的 if 语句更改为 if 'SEQADV' in line.split() and 'MUTATION' in line.split():

【讨论】:

  • 谢谢你,我不知道为什么我没有想到这个,但它确实有效
  • 没问题。乐于助人。
猜你喜欢
  • 2022-01-10
  • 1970-01-01
  • 2021-06-05
  • 1970-01-01
  • 2018-10-31
  • 2018-02-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多