在python中声明变量

时间:2011-08-19 21:51:44

标签: python

我想解析一个文件来搜索一个单词然后打印下一行我写了如下的python脚本

infile = open("s.sdf","r")
output = open("sample.txt","w")
d = None
HD = None
HA = None
M = None

for line in infile:
      if line.startswith(">  <PUBCHEM_COMPOUND_CID>"):
         d = infile.next().strip()
         print d      
      elif line.startswith(">  <PUBCHEM_CACTVS_HBOND_DONOR>"):
         HD = infile.next().strip()
         print HD
      elif line.startswith(">  <PUBCHEM_CACTVS_HBOND_ACCEPTOR>"):
         HA = infile.next().strip()
         print HA
      elif line.startswith(">  <PUBCHEM_MOLECULAR_WEIGHT>"):
         M = infile.next().strip()
         print M

      print "%s \t  %s  \t  %s  \t  %s" %(d,HD,HA,M)
      output.write("%s  \t  %s  \%s \t  %s" %(d,HD,HA,M))

但不幸的是我收到如下错误

None None None None

None None None None

None None None None

None None None None
.......

有谁能告诉我如何解决这个问题..

先谢谢

<磷>氮

1 个答案:

答案 0 :(得分:1)

要跳过与这些字符串不匹配的行,请添加一个检查:

if any(bool(x) for x in d, HD, HA, M):
    print ...
    output.write

尝试在调试器中运行脚本:

$ python -m pdb your_script.py

看看有什么变量,有什么不对。由于PDB不方便,您可能需要安装ipdbpudb