Python Google Translate API

Source: Internet
Author: User

Reference from: http://www.icourse163.org/learn/BIT-1001870001?tid=1001962001#/learn/forumdetail?pid=1003366321

Import requestsfrom BS4 import beautifulsoup def gethtmltext (URL): try:r = Requests.get (URL, timeout=30)        R.raise_for_status () return r.text except:print ("Get HTML text failed!") return 0 def google_translate_etoc (to_translate, from_language= "en", to_language= "CH-CN"): #根据参数生产提交的网址 Base_url = " https://translate.google.cn/m?hl={}&sl={}&ie=utf-8&q={} "url = Base_url.format (To_language, From_ Language, to_translate) #获取网页 html = gethtmltext (URL) If Html:soup = BeautifulSoup (HTML, "Html.parse R ") #解析网页得到翻译结果 Try:result = Soup.find_all (" div ", {" Class ":" T0 "}) [0].text Except:print ("        Translation failed! ")    result = "" Return resultdef Google_translate_ctoe (to_translate, from_language= "CH-CN", to_language= "en"): #根据参数生产提交的网址 base_url = "https://translate.google.cn/m?hl={}&sl={}&ie=utf-8&q={}" url = Base_url.format ( To_language, From_language,to_translate) #获取网页 html = gethtmltext (URL) If Html:soup = BeautifulSoup (HTML, "Html.parser") #解析网页得到翻译结果 Try:result = Soup.find_all ("div", {"Class": "T0"}) [0].text except:print ("Translatio        n failed! ") result = "" Return Resultdef Main (): While true:inp = int (input ("Chinese-englisth is 1, 中文版 To Chinese is 2: ")) if InP = = 1:words = input (" Please enter Chinese: ") Print (Google_translate_ctoe ( words) Else:words = input ("Please input 中文版:") print (Google_translate_etoc (words)) m Ain ()

  

Python Google Translate API

Related Article

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.