Python implements translation capabilities

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.