Python Forum

Full Version: Why doesn't it show me anything in print?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Why doesn't it show me anything in print?

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")) #Chinese to English
print(translate("你吃饭了么&#xff1f;", "ja","zh-CN")) #Chinese to Japanese
print(translate("about your situation", "zh-CN","en")) #English to Chinese
print(translate("about your situation", "en","ro")) #English to Chinese
All your requests return a 404 response. Reason is "Not Found". My guess is the url string is all messed up. See if you can get it to work using a literal for the url string. If you can get that, then try to duplicate the literal url string by passing and processing arguments.
You should use the Cloud Translation API they not so happy if not using it like you do now.
Translate terms Wrote:The Google Translate API must be used for user-generated translations.
Automated or batched queries of any kind are strictly prohibited.
Can get a free Api key if register.
If i do quick usage test.
import requests

api_key = "xxxxx"
text = "hello"
lang = "es"

response = requests.get(
    f"https://translation.googleapis.com/language/translate/v2?target={lang}&key={api_key}&q={text}"
)
>>> js = response.json()
>>> js
{'data': {'translations': [{'detectedSourceLanguage': 'en',
                            'translatedText': 'Hola'}]}}
>>> js['data']['translations'][0]['translatedText']
'Hola'