用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
.......

谁能告诉我怎么解决这个问题?

Thanks in Advance

N

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

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

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

$ python -m pdb your_script.py

,看看有哪些变量,哪里出了问题。由于PDB不方便,您可能希望安装ipdbpudb

最新更新