#!/usr/bin/python
# -*- coding:utf-8 -*-
#通过有道翻译来进行内容翻译
import urllib2
import urllib
import json
#---------翻译方法定义 start---------#
def transfer( transferStr , lanSource ='auto' ):
data = {'type':lanSource,'i':transferStr,'doctype':'json','xmlVersion':'1.8','keyfrom':'fanyi.web','ue':'UTF-8','action':'FY_BY_CLICKBUTTON','typoResult':'true'}
data = urllib.urlencode(data).encode('utf-8')
response = urllib2.urlopen(url,data)
content = response.read().decode('utf-8')
result = json.loads(content)
result = result['translateResult'][0][0]['tgt'].encode('utf-8')
return result
#---------翻译方法定义 end--------#
language = ['中文-日语','中文-英语','中文-韩语','中文-法语','中文-俄语','中文-西班牙语','auto'] #翻译语言列表
lanMap = ['ZH_CN2EN','ZH_CN2JA','ZH_CN2KR','ZH_CN2FR','ZH_CN2RU','ZH_CN2SP'] #翻译语言映射
url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=null" #翻译的url地址
lanStr = ''
for i in range(len(language)):
lanStr += str(i) + '--->' + language[i] + " "
num = int(raw_input('请输入你要翻译的语言: %s' % lanStr))
len = len(lanMap)
if(num > len):
raw_input('输入错误,按任意键退出!')
exit()
elif num == len:
type = 'auto'
else:
type = lanMap[num]
print("你选择的翻译语种是:%s" % language[num])
keywords = raw_input('请输入你要翻译的内容:')
result = transfer(keywords,type)
print("%s(%s)翻译的结果为:%s" %(keywords,language[num],result))