简体   繁体   English

如何使用Python从Google Translate API访问JSON转换

[英]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. 我正在尝试学习塞尔维亚自动取款机,并让自己得到一个包含最常用单词的csv文件。
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. 我现在想做的是让我的脚本通过API将每个单词放入Google Translate,并将此翻译保存到同一文件中。
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. 由于我是Python和JSON的初学者,因此我对如何使用从API获取的JSON感到非常困惑。

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. 终端为我打印的内容如下所示: {u'translations': [{u'translatedText': u'allein'}]}其中“ allein”是{u'translations': [{u'translatedText': u'allein'}]}单词的德语翻译。

How can I get to the "allein"? 我怎么去“ 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. 我试图通过实现Python附带的json编码器和解码器来解决这个问题,但是我无法弄清楚。

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. 因为Google的翻译服务可以为给定的文本提供多种翻译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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