1, open the file example:
1 file=open (' D:\\python\\untitled\\hello.txt ', ' R ', encoding= ' Utf-8 ') 2 Data=file.read () 3 print (data) 4 file.close ()
2, the use of Urllib Library request page for a simple translation, request Baidu translation, will be translated content as parameters to Baidu, and then assign the results to parameters, and finally print out:
On the code:
1 Import urllib.request 2 import urllib.parse 3 import JSON 4 5 content=input ("===== Please enter what you want to translate: =====\n") 6 7 url= ' Http://fanyi.baidu.com/v2transapi ' 8 data={} 9 data[' from ']= ' zh ' data[' to ']= ' en ' all data[' transtype ']= ' Translang ' 12 data[' Simple_means_flag ']= ' 3 ' data[' query ']=content14 data=urllib.parse.urlencode (data). Encode (' Utf-8 ') 15 Response=urllib.request.urlopen (Url,data) Html=response.read () decode (' Utf-8 ') target=json.loads (HTML) 18 Print ("Translated result:%s"% (target[' trans_result ' [' Data '][0][' DST ')])
Achieve results
Python implements translation capabilities