Home >  > 调用Google的API接口翻译文章

调用Google的API接口翻译文章

0

一、运行的效果如下:
Snap62

二、源码如下:

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()

可参考的:
https://github.com/ssut/py-googletrans
https://github.com/terryyin/translate-python
https://github.com/yucongo/mgoogle_translate

updated on July-12-2020
三、写成一个类

import requests
import json
from bs4 import BeautifulSoup

def get_ip():
    url = "http://webapi.http.zhimacangku.com/getip?num=1&type=2&pro=&city=0&yys=0&port=1&time=1&ts=0&ys=0&cs=0&lb=1&sb=0&pb=4&mr=1&regions="

    html = requests.get(url)
    html = html.text
    print(html)

    json_data = json.loads(html)
    ip_list = []
    # print(json_data['data'])
    for i in json_data['data']:
        # print("http://"+i['ip']+":"+str(i['port']))
        ip = "http://"+i['ip']+":"+str(i['port'])
        # print("*"*10)
        ip_list.append(ip)
    return ip_list

proxy_ip = get_ip()[0]
proxies = { "http": proxy_ip }   


class Translate():
    def __init__(self, content, proxy):
        self.content = content
        self.proxy = proxy

    
    def getHTMLText(self,url):
        try:
            r = requests.get(url, proxies = self.proxy,timeout=30)
            print(self.proxy)
            r.raise_for_status()
            return r.text
        except:
            print("Get HTML Text Failed!")
            return 0
        

    def get_chinese_conetent(self,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, self.content)

        # 获取网页
        html = self.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 get_english_conetent(self,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, self.content)

        # 获取网页
        html = self.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


a = "i love you very much"
c = Translate(a, proxies)
r = c.get_chinese_conetent()
print(r)

用法:

from google_translate import Translate

t2 = Translate(a)
ch_content = t2.get_chinese_conetent()
print(ch_content)

四、注意事项
1.如果英文中有“&”这个符号,会影响翻译,就是到了&就断了,后面的句子不翻译。解决方案:

x= x.replace("&","and")
content = content.replace("#","")  #这个符号也会造成翻译的问题
本文暂无标签

发表评论

*

*