简体   繁体   English

在python中声明变量

[英]Declaring variables in python

I wanted parse a file to search one word and print next line i have written python script as follows 我想解析一个文件以搜索一个单词并打印下一行我已经编写了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))

But unfortunately i getting an error as follows 但是不幸的是我得到如下错误

None None None None

None None None None

None None None None

None None None None
.......

Can anybody tell me how to solve this.. 谁能告诉我如何解决这个问题。

Thanks in Advance 提前致谢

N ñ

To skip lines that do not match those strings add a check: 要跳过与这些字符串不匹配的行,请添加检查:

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

Try running the script in a debugger: 尝试在调试器中运行脚本:

$ python -m pdb your_script.py

and see what variables are there and what's wrong. 并查看其中存在哪些变量以及出了什么问题。 Since PDB is not convenient, you might want to install ipdb or pudb . 由于PDB不方便,因此您可能需要安装ipdbpudb

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM