I wanted parse a file to search one word and print next line i have written python script as follows
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
Jim Garrison
87k20 gold badges162 silver badges197 bronze badges
1 Answer 1
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.
SingleNegationElimination
157k35 gold badges270 silver badges306 bronze badges
answered Aug 19, 2011 at 22:16
culebrón
37k21 gold badges78 silver badges117 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
{}button in the SO editor to format your code (or indent everything 4 spaces). I fixed it for you.startswithconditions are matching. Post some of your data. Also, add someprintstatements under the conditions so you can see when they are getting triggered (if they are) -- debugging 101..sdfextension, which turns out to be a chemical data file. It uses angle brackets, but only to identify header lines. en.wikipedia.org/wiki/SD_format#SDF