#! /usr/bin/python # -*- coding: utf-8 -*- ####################################### # #e.g. how are you<ENTER> # 你好<ENTER> # 2013.5.16 ####################################### import urllib.request,urllib.parse import os,sys import json API_KEY = 'awG627Qe2BTnrexw678GnYTi' DU_TRANS_URL = 'http://openapi.baidu.com/public/2.0/bmt/translate?client_id=%s&q=%s&from=%s&to=%s' def translate(src,flag): if flag == 'c2e':#chinese to english srclanguage = 'zh' destlanguage = 'en' elif flag == 'e2c':# english to chinese srclanguage = 'en' destlanguage = 'zh' elif flag == 'o2o':#auto srclanguage = 'auto' destlanguage = 'auto' else: print('Wrong Flag, use c2e(chinese to english) or e2c(english to chinese)!!') exit(-1) try: response = urllib.request.urlopen(DU_TRANS_URL%(API_KEY,urllib.parse.quote(src),srclanguage,destlanguage)) except Exception as e: raise Exception('Connect to Server Fail!' + str(e)) jsonData = json.loads(response.read().decode('utf-8')) if 'error_code' in response: raise Exception('trans error:' + jsonData['error_msg']) print('-->',jsonData['trans_result'][0]['dst']) if __name__=='__main__': while 1: translatesting = input() if translatesting == '':#空串结束 exit(0) translatesting_l = translatesting.split() translate(translatesting,'o2o') #实现判断输入的字符串是中文还是英文,转换成unicode编码后进行判断,未实现。 # if 是英文: # translate(translatesting,'e2c') # else是中文: # translate(translatesting,'c2e')