Python Forum
Why doesn't it show me anything in print? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Why doesn't it show me anything in print? (/thread-38346.html)



Why doesn't it show me anything in print? - Melcu54 - Sep-30-2022

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



RE: Why doesn't it show me anything in print? - deanhystad - Sep-30-2022

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.


RE: Why doesn't it show me anything in print? - snippsat - Oct-01-2022

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'