1 #" "2 #Created on 2018-5-263 # 4 #@author: Yaoshuangqi5 #" "6 Importurllib.request7 ImportUrllib.parse8 ImportJSON9 Ten classYoudaofanyi (): One """ A Youdao Dictionary API - """ -VERSION = 1.1 theURL ='http://fanyi.youdao.com/openapi.do' -Key_from ='Dic-eve' -KEY ='975360059' -TYPE ='Data' + #Optional value XML, JSON -Doc_type ='JSON' + defTranslate (self, text): A """ at translation method, passing in the text to be translated, returning the result dictionary - """ - #Parameters -params = {'Keyfrom': Self. Key_from,'Key': Self. KEY,'type': Self. TYPE,'DOCTYPE': Self. Doc_type,'version': Self. VERSION,'Q': Text} -RESP = Urllib.request.urlopen (self. URL, Urllib.parse.urlencode (params). Encode (encoding='Utf_8')) -data = Resp.read (). Decode ("Utf_8") in Print('Youdao API translation content:%s'%data) - returnjson.loads (data) to + defFormat_for_command (self, text): - """ the format translation results for the command line * """ $data =Main (text)Panax Notoginseng #TODO: Formatting strings - ifData: the Print('Youdao Translation:') + Print('\ t Original text:', Data.get ('Query', text)) ATranslation = Data.get ('translation', None) theexplains = data['Basic']['explains'] + ifTranslation: - forTinchTranslation: $ Print('\ t translation:', T) $ ifexplains: - Print('\ t Explanation:', explains) - Else: the Print('The word was not found') - Wuyi defMain (text): the ifText andText.strip ()! ="': - returnYoudaofanyi (). Translate (text) Wu - if __name__=='__main__': About whileTrue: $Content = input ('Please enter the translated content:') - ifcontent: - Youdaofanyi (). Format_for_command (content) - Else: A Print('Youdao Translation: \n\t tip: You have quit!! ') + Break
Youdao Translation API Link: Http://fanyi.youdao.com/openapi?path=data-mode
Simple implementation of Python invoke Youdao API interface (latest)