Python调用谷歌翻译API实现文本翻译


本文将用Python调用谷歌翻译API实现文本翻译;

使用Python向谷歌翻译URL进行GET请求,得到网页内容后使用正则表达式进行解析,获得翻译结果;

实现代码

import re
import html
from urllib import parse
import requests

GOOGLE_TRANSLATE_URL = 'http://translate.google.cn/m?q=%s&tl=%s&sl=%s'

def translate(text, to_language="auto", text_language="auto"):

    text = parse.quote(text)
    url = GOOGLE_TRANSLATE_URL % (text,to_language,text_language)
    response = requests.get(url)
    data = response.text
    expr = r'(?s)class="(?:t0|result-container)">(.*?)<'
    result = re.findall(expr, data)
    if (len(result) == 0):
        return ""

    return html.unescape(result[0])

print(translate("你吃饭了么?", "en","zh-CN")) #汉语转英语
print(translate("你吃饭了么?", "ja","zh-CN")) #汉语转日语
print(translate("about your situation", "zh-CN","en")) #英语转汉语

输出:

Have you eaten?
食事はしましたか?
关于你的情况

如需转载,请注明出处;本文地址:https://www.perfcode.com/p/Python-calls-google-translate-api.html