zoukankan      html  css  js  c++  java
  • 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()
    

      

  • 相关阅读:
    【java】java 中 byte[]、File、InputStream 互相转换
    【java】java base64编码与解码
    git初级使用教程
    git学习五:eclipse使用git下载项目
    git学习四:eclipse使用git提交项目
    mybatis连接mysql数据库插入中文乱码
    SpringMVC加载配置Properties文件的几种方式
    zip 压缩文件夹
    java IOUtils下载图片
    spring工具类获取bean
  • 原文地址:https://www.cnblogs.com/wnzhong/p/6666911.html
Copyright © 2011-2022 走看看