import urllib
fko=open("ko.txt","r")# as a input gets KO list in a text file
fkoec=open("ko_ec.txt","w")# as a output file returne a KO-EC in a text file
fec=open("ec.txt","w")# as a output file return all ECs in a text file
lec=[]
while 1:
	text=fko.readline().rstrip('\n')
	if text=="":
		break
	else:
		print(text)		
		url='http://www.genome.jp/dbget-bin/www_bfind_sub?mode=bfind&max_hit=1000&locale=en&serv=kegg&dbkey=orthology&keywords='+text
		#print(url)
		f = urllib.urlopen(url)
		myfile = f.read()
		#print(myfile)
		h1=myfile.find('style="margin-left:2em"> ')
		h2=myfile.find('[EC:')
		h3=h2
		if h3>0:
        		while myfile[h3]!=']':
            			h3=h3+1
			st1=myfile[h2+4:h3]
		else:
			st1=""
		#print(st1)
		if st1!="" and (' ' in st1)==False: 
			if ('-' in st1)==False:
				fkoec.write(text[0:6])
				fkoec.write('\t')	
				fkoec.write(st1)
				fkoec.write('\n')
				if st1 not in lec: 
					lec.append(st1)				
		elif st1!="" and (' ' in st1)==True:
			while st1!="":
				h1=st1.find(' ')
				if h1!=-1:
					st2=st1[0:h1]
				else:
					st2=st1
					st1=""
				#print(st2)
				st1=st1[h1+1:len(st1)]
				#print(st1)
				#input('ver=')
				if ('-' in st2)==False:
					fkoec.write(text[0:6])
					fkoec.write('\t')
					fkoec.write(st2)
					fkoec.write('\n')
					if st2 not in lec: 
						lec.append(st2)
fko.close()
fkoec.close()
lec.sort()
i=0
while i<len(lec):
	fec.write(lec[i])
	fec.write('\n')
	i+=1
fec.close()
