Reputation: 5071
I am trying to find a way to interact with the Google translation service. I would like to be able to pass to the service a list with strings in a source language and get back a list with values strings in the target language.
Working from Python, I have found some relevant code here: https://github.com/google/google-api-python-client/blob/master/samples/translate/main.py
I tried the code and it works. See below:
from __future__ import print_function
__author__ = '[email protected] (Joe Gregorio)'
from googleapiclient.discovery import build
def main():
# Build a service object for interacting with the API. Visit
# the Google APIs Console <http://code.google.com/apis/console>
# to get an API key for your own application.
service = build('translate', 'v2',
developerKey='AIzaSyCT4Ds5GuytOZnxGav492RAUvN508daobAVo')
print(service.translations().list(
source='el',
target='en',
q=['Είμαι πολύ ευτυχής που σας βλέπω σήμερα εδώ', 'Η κόρη μου θα χαρεί πολύ να σας δει']
).execute())
if __name__ == '__main__':
main()
When run this code printed the following output:
{'translations': [{'translatedText': 'I am very happy to see you here today'}, {'translatedText': 'My daughter will be very pleased to see you'}]}
However as I said, the code above prints the returned results to the screen. What I would like instead would be to store the translated text into an object that eventually I would make it a pandas object.
So I tried to ammend it in this way - see below:
from __future__ import print_function
__author__ = '[email protected] (Joe Gregorio)'
from googleapiclient.discovery import build
def main():
# Build a service object for interacting with the API. Visit
# the Google APIs Console <http://code.google.com/apis/console>
# to get an API key for your own application.
service = build('translate', 'v2',
developerKey='AIzaSyCT4Ds5GuytOZnxGav492RAUvN508daobAVo')
result = service.translations().list(
source='el',
target='en',
q=['Είμαι πολύ ευτυχής που σας βλέπω σήμερα εδώ', 'Η κόρη μου θα χαρεί πολύ να σας δει']
).execute()
return result
if __name__ == '__main__':
main()
However when I tried to display of the object "result" I got the following exception:
NameError: name 'result' is not defined
Upvotes: 0
Views: 85
Reputation: 479
How are you trying to "display result"?
It looks like your code successfully creates result, but then main()
returns it... to where? How are you calling main and using what it returns?
You can't access local function variables (e.g. result) outside the function that defines them.
Likely, what you want is for this code to be a function that returns the result to another function/program, that then uses the result returned.
E.g.
def your_main_program():
result = the_function_you_currently_have() #currently called main()
# do something with the result
Upvotes: 1