Python Forum
Why doesn't it show me anything in print?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why doesn't it show me anything in print?
#1
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
Reply
#2
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.
Reply
#3
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'
Melcu54 likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  PDF properties doesn't show created or modified date Pedroski55 4 1,076 Jun-19-2023, 08:09 AM
Last Post: Pedroski55
  PIL Image im.show() no show! Pedroski55 2 962 Sep-12-2022, 10:19 PM
Last Post: Pedroski55
  PIL Image im.show() no show! Pedroski55 6 4,888 Feb-08-2022, 06:32 AM
Last Post: Pedroski55
  Why doesn't this print statement work? stylingpat 10 5,724 Mar-23-2021, 07:54 PM
Last Post: buran
  Line of code to show dictionary doesn't work MaartenRo 2 2,429 Jul-28-2020, 03:58 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020