Python Google Translate API


參考自:http://www.icourse163.org/learn/BIT-1001870001?tid=1001962001#/learn/forumdetail?pid=1003366321

import requests
from 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.parser")
     
    #解析網頁得到翻譯結果    
    try:
        result = soup.find_all("div", {"class":"t0"})[0].text
    except:
        print("Translation Failed!")
        result = ""
         
    return result

def 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("Translation Failed!")
        result = ""
         
    return result

def main():
    while True:
        inp = int(input("Chinese to Englisth is 1, English to Chinese is 2:    "))
        if inp == 1:
            words = input("請輸入中文:    ")
            print(google_translate_CtoE(words))
        else:
            words = input("Please input English:    ")
            print(google_translate_EtoC(words))

main()

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM