#!/usr/bin/python
#-*-Coding:utf-8-*-
#通过有道翻译来进行内容翻译
Import Urllib2
Import Urllib
Import JSON
#---------Translation Method definition 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
#---------Translation Method definition End--------#
Language = [' Chinese-Japanese ', ' Chinese-English ', ' Chinese-Korean ', ' Chinese-French ', ' Chinese-Russian ', ' Chinese-Spanish ', ' 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] + "\ n"
num = Int (raw_input (' Please enter the language you want to translate: \n%s '% lanstr))
Len = Len (lanmap)
if (num > Len):
Raw_input (' input error, press any key to exit! ‘)
Exit ()
elif num = = Len:
Type = ' Auto '
Else
Type = Lanmap[num]
Print ("The translation language you selected is:%s"% language[num])
Keywords = raw_input (' Please enter what you want to translate: ')
result = Transfer (Keywords,type)
Print ("%s (%s) translated result:%s"% (Keywords,language[num],result))
Example of a Python translation dictionary