Search code examples
python-3.xpython-requestsurllibgoogle-translategoogle-translator-toolkit

Google Translate API : Multiple input texts - Python


I am struggling to find a way to input multiple texts in Google Translate API. My setup includes the following things.

My Question : How to add multiple texts to the input. ? Because the following code is not making any sense to me.

data = {'q':'cat', 'q':'dog','source':source,'target':target,'format':'html'}

This is my code.

data = {'q':'This is Text1', 'q':'This is Text2', 'q':'This is Text3', source':source,'target':target,'format':'html'}
_req = urllib.request.Request("https://translation.googleapis.com/language/translate/v2?key="+API_KEY)
_req.add_header('Content-length', len(data))
_req.data = urllib.parse.urlencode(data).encode("utf-8")
response = Connector._get(_req,_session)

Connector._get() is in some other file and it internally calls urllib.request.build_opener with data.

Thanks!


Solution

  • To post multiple parameters (with the same name) in Python for an HTTP request, you can use a list for the values. They'll be added to the URL like q=dog&q=cat.

    Example:

    headers = { 'content-type': 'application/json; charset=utf-8' }
    params = {'q': ['cat', 'dog'],'source':source,'target':target,'format':'html'}
    response = requests.post(
                "https://translation.googleapis.com/language/translate/v2?key=",
                headers=headers,
                params=params
            )
    

    Specifically, params = {'q': ['cat', 'dog']} is relevant to your question.