from operator import itemgetter
import os
import urllib
import json
engdic={}
count=0
count_new=0
if(not os.path.isfile("engdic.txt")):
print "no dict file, I'll make one!"
else:
for line in open("engdic.txt"):
cols=line.split('|')
if(len(cols)==2):
engdic[cols[0].strip()]=(cols[1].strip(),'')
elif (len(cols)==3):
engdic[cols[0].strip()]=(cols[1].strip(),cols[2].strip())
else:
continue
count=count+1
print 'Find dict, total',count,'words'
output=open("engdic_t.txt",'w')
output2=open("chndic_t.txt",'w')
while 1:
word=raw_input("Please input word: ")
if (word==''):
break
url='http://fanyi.youdao.com/openapi.do?keyfrom=HCocoa-blog&key=582126642&type=data&doctype=json&version=1.1&q='+word
page=urllib.urlopen(url)
data=page.read()
#data=data.decode("UTF-8", 'ignore').encode("gbk", 'ignore')
ddata=json.loads(data)
if (ddata['errorCode']!=0 or not 'web' in ddata):
print "sorry, but i don't konw what it is, plz input another word."
continue
web=''
for cols in ddata['web'][0]['value']:
web=web+cols.encode("gbk", 'ignore')+','
print word,ddata['translation'][0].encode("gbk", 'ignore'),web[:-1]
engdic[word]=(ddata['translation'][0].encode("gbk", 'ignore'),web[:-1])
count_new=count_new+1
sorteddic=sorted(engdic.iteritems(), key=itemgetter(0)) #retuen tuple
for words in sorteddic:
str= '%-15s| %-10s| %s'%(words[0],words[1][0],words[1][1])
print str
output.write(str+'\n')
output.close()
sorteddic=sorted(engdic.iteritems(), key=itemgetter(1)) #retuen tuple
for words in sorteddic:
str= '%-15s| %-10s| %s'%(words[1][0],words[0],words[1][1])
output2.write(str+'\n')
output2.close()
print 'Processed',count_new,'new words, total words number is',count+count_new
if(os.path.isfile("engdic.txt")):
os.remove('engdic.txt')
os.rename('engdic_t.txt','engdic.txt')
if(os.path.isfile("chndic.txt")):
os.remove('chndic.txt')
os.rename('chndic_t.txt','chndic.txt')
raw_input()