Created
April 8, 2018 14:33
-
-
Save curiousleo/b6bac7fe159879d5d734a9d6ec929a93 to your computer and use it in GitHub Desktop.
Convert IUPAC to SMILES and vice versa
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import urllib.error | |
import urllib.parse | |
import urllib.request | |
SMILES_URL_TEMPLATE = 'http://cactus.nci.nih.gov/chemical/structure/{}/smiles' | |
IUPAC_URL_TEMPLATE = 'http://cactus.nci.nih.gov/chemical/structure/{}/iupac_name' | |
def retrieve(url): | |
with urllib.request.urlopen(url) as f: | |
return f.read() | |
def iupac2smiles(iupac): | |
quoted_iupac = urllib.parse.quote(iupac) | |
smiles_url = SMILES_URL_TEMPLATE.format(quoted_iupac) | |
return retrieve(smiles_url).decode('utf-8') | |
def smiles2iupac(smiles): | |
quoted_smiles = urllib.parse.quote(smiles) | |
iupac_url = IUPAC_URL_TEMPLATE.format(quoted_smiles) | |
return retrieve(iupac_url).decode('utf-8') | |
if __name__ == '__main__': | |
import sys | |
convert = None | |
src = None | |
dst = None | |
if sys.argv[1] == 'iupac2smiles': | |
convert = iupac2smiles | |
src = 'iupac' | |
dst = 'smiles' | |
elif sys.argv[1] == 'smiles2iupac': | |
convert = smiles2iupac | |
src = 'smiles' | |
dst = 'iupac' | |
else: | |
print('Usage: python3 convert.py <iupac2smiles|smiles2iupac> < <filename>', file=sys.stderr) | |
sys.exit(1) | |
for name in map(str.strip, sys.stdin): | |
try: | |
print('[{src}] {original}\n= [{dst}] {converted}'.format( | |
src=src, dst=dst, original=name, converted=convert(name))) | |
except urllib.error.HTTPError as e: | |
print('[{src}] {original}\n: error {error}'.format( | |
src=src, original=name, error=e.code)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment