實例如下:
import urllib.requestimport urllib.parseimport jsonwhile True: content = input('請輸入需要翻譯的內(nèi)容(退出輸入Q):') if content == 'Q': break else: url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=http://www.youdao.com/' data = {} data['type'] = 'AUTO' data['i'] = content data['doctype'] = 'json' data['xmlVersion'] = '1.8' data['keyfrom'] = 'fanyi.web' data['ue'] = 'UTF-8' data['action'] = 'FY_BY_CLICKBUTTON' data['typoResult'] = 'true' data = urllib.parse.urlencode(data).encode('utf-8') response = urllib.request.urlopen(url, data) html = response.read().decode('utf-8') target = json.loads(html) print('翻譯的結(jié)果:%s' % target['translateResult'][0][0]['tgt'])程序執(zhí)行情況:

這里要注意的是兩個函數(shù)urllib.request.urlopen()與urllib.parse.urlencode()。
urllib.request.urlopen()其實不止一個參數(shù),有好幾個哦,其中第二個是data,data應(yīng)該是一個buffer的標準應(yīng)用程序/ x-www-form-urlencoded格式(python標準庫原文:data should be a buffer in the standard application/x-www-form-urlencoded format)。urllib.parse.urlencode()函數(shù)接受一個映射或序列集合,并返回一個字符串的格式(python標準庫原文:The urllib.parse.urlencode() function takes a mapping or sequence of 2-tuples and returns a string in this format)。我們可以看看urllib.parse.urlencode()的結(jié)果是什么樣的:

上圖的結(jié)果剛好與urllib.request.urlopen()的data參數(shù)的數(shù)據(jù)類型要求一致了。
注意,上面urlopen當中的url,這個是分析有道翻譯頁面的真實的Request URL:


以上這篇python利用有道翻譯實現(xiàn)"語言翻譯器"的功能實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點
疑難解答
圖片精選