2

I'm trying to learn Serbian atm and got myself a csv file with the most frequently used words.
What I'd like to do now is have my script put each word into Google Translate via the API and save this translation to the same file.
Since I'm a total Python and JSON beginner I am massively confused about how to use the JSON I'm getting from the API.

How do I get to the translation?

from sys import argv
from apiclient.discovery import build
import csv
import json

script, filename = argv
serbian_words = []

# Open a CSV file with the serbian words in one column (one per row)
with open(filename, 'rb') as csvfile:

    serbianreader = csv.reader(csvfile)

    for row in serbianreader:

        # Put all words in one single list
        serbian_words.extend(row)

        # send that list to google item by item to have it translated
        def main():

            service = build('translate', 'v2',
            developerKey='xxx')

            for word in serbian_words:

                translation = service.translations().list(
                    source='sr',
                    target='de',
                    q = word
                    ).execute()

                    print translation # Until here everything works totally fine.



if __name__ == '__main__':
  main()

What Terminal prints for me looks like this {u'translations': [{u'translatedText': u'allein'}]} where the "allein" is the german translation of a serbian word.

How can I get to the "allein"? I've tried to figure this out by trying to implement the json Encoder and Decoder that comes with Python, but I can't figure it out.

I'd love any help on this and would be very grateful.

1 Answer 1

1

You can use item access to get to the innermost string:

translation['translations'][0]['translatedText']

or you could loop over all the translations listed (it's a list):

for trans in translation['translations']:
    print trans['translatedText']

as Google's translation service can give more than one translation for a given text.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.