简体   繁体   中英

How to access JSON translation from Google Translate API with Python

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM